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.