Is it ok to use a Guava Cache of maximum size 1?
I'm reading that sometimes there can be evictions even before that maximum size is reached.
However, I only need one cache entry. So I'm wondering what value to set for maximum size that would be safe, but not excessive.
You should be able to use Cache.cleanUp() as explained in When Does Cleanup Happen? and test whether a maximum size of 1 suites your needs or not.
e.g. The following shows that using a LoadingCache with maximum size of 1 will not evict an existing entry until a different entry is loaded to take its place:
final LoadingCache<Character, Integer> loadingCache = CacheBuilder.newBuilder()
.maximumSize(1)
.build(new CacheLoader<Object, Integer>() {
private final AtomicInteger loadInvocationCount = new AtomicInteger();
@Override
public Integer load(Object key) throws Exception {
return loadInvocationCount.getAndIncrement();
}
});
assert loadingCache.size() == 0;
assert loadingCache.getUnchecked('a') == 0;
assert loadingCache.size() == 1;
loadingCache.cleanUp();
assert loadingCache.size() == 1;
assert loadingCache.getUnchecked('a') == 0;
assert loadingCache.size() == 1;
assert loadingCache.getUnchecked('b') == 1;
assert loadingCache.size() == 1;
loadingCache.cleanUp();
assert loadingCache.size() == 1;
assert loadingCache.getUnchecked('a') == 2;
assert loadingCache.size() == 1;
loadingCache.cleanUp();
assert loadingCache.size() == 1;
Note that this may be specific to the type of LoadingCache being built so you will need to test whatever configuration you plan to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With