Skip to content

Instantly share code, notes, and snippets.

@zetlan
Created April 7, 2023 15:14
Show Gist options
  • Save zetlan/29d0d260d2296b355b99ed1231dc7281 to your computer and use it in GitHub Desktop.
Save zetlan/29d0d260d2296b355b99ed1231dc7281 to your computer and use it in GitHub Desktop.
package com.zola.service.marketplace.core;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.junit.jupiter.api.Test;
import java.util.Objects;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
class LoadingCacheTest {
static class KeyClass {
private String key;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Override
public int hashCode() {
return Objects.hashCode(key);
}
public KeyClass(String someKey) {
this.setKey(someKey);
}
}
@Test
void testLoadingCacheError() {
LoadingCache<KeyClass, String> loadingCache = Caffeine.newBuilder()
.recordStats()
.maximumSize(2)
.build(this::cacheLoader);
var key1 = new KeyClass("key1");
var key2 = new KeyClass("key2");
assertThat(loadingCache.get(key1)).isEqualTo(key1.getKey());
assertThat(loadingCache.get(key2)).isEqualTo(key2.getKey());
// So far, so good. Now let's mutate the keys:
key1.setKey("some other key1");
key2.setKey("some other key2");
assertThat(loadingCache.get(key1)).isEqualTo("some other key1");
assertThat(loadingCache.get(key2)).isEqualTo("some other key2");
// and finally, let's add a third entry to the cache, which should force eviction
var key3 = new KeyClass("key3");
assertThat(loadingCache.get(key3)).isEqualTo(key3.getKey());
/*
The test will pass, but should produce output like this:
Apr 07, 2023 11:13:04 AM com.github.benmanes.caffeine.cache.BoundedLocalCache logIfAlive
SEVERE: An invalid state was detected that occurs if the key's equals or hashCode was modified while it
resided in the cache. This violation of the Map contract can lead to non-deterministic behavior
(key: LoadingCacheTest$KeyClass@71d90b6e).
*/
}
private String cacheLoader(KeyClass keyObject) {
return keyObject.getKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment