use of com.github.benmanes.caffeine.cache.RemovalCause in project caffeine by ben-manes.
the class CacheExpirationTest method testRemovalListener_expireAfterWrite.
public void testRemovalListener_expireAfterWrite() {
FakeTicker ticker = new FakeTicker();
final AtomicInteger evictionCount = new AtomicInteger();
final AtomicInteger applyCount = new AtomicInteger();
final AtomicInteger totalSum = new AtomicInteger();
RemovalListener<Integer, AtomicInteger> removalListener = new RemovalListener<Integer, AtomicInteger>() {
@Override
public void onRemoval(Integer key, AtomicInteger value, RemovalCause cause) {
if (cause.wasEvicted()) {
evictionCount.incrementAndGet();
totalSum.addAndGet(value.get());
}
}
};
CacheLoader<Integer, AtomicInteger> loader = new CacheLoader<Integer, AtomicInteger>() {
@Override
public AtomicInteger load(Integer key) {
applyCount.incrementAndGet();
return new AtomicInteger();
}
};
LoadingCache<Integer, AtomicInteger> cache = CaffeinatedGuava.build(Caffeine.newBuilder().removalListener(removalListener).expireAfterWrite(10, MILLISECONDS).executor(MoreExecutors.directExecutor()).ticker(ticker::read), loader);
// Increment 100 times
for (int i = 0; i < 100; ++i) {
cache.getUnchecked(10).incrementAndGet();
ticker.advance(1, MILLISECONDS);
}
assertEquals(evictionCount.get() + 1, applyCount.get());
int remaining = cache.getUnchecked(10).get();
assertEquals(100, totalSum.get() + remaining);
}
Aggregations