Search in sources :

Example 1 with RemovalCause

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);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FakeTicker(com.google.common.testing.FakeTicker) TestingRemovalListeners.countingRemovalListener(com.google.common.cache.TestingRemovalListeners.countingRemovalListener) CountingRemovalListener(com.google.common.cache.TestingRemovalListeners.CountingRemovalListener) RemovalListener(com.github.benmanes.caffeine.cache.RemovalListener) RemovalCause(com.github.benmanes.caffeine.cache.RemovalCause)

Aggregations

RemovalCause (com.github.benmanes.caffeine.cache.RemovalCause)1 RemovalListener (com.github.benmanes.caffeine.cache.RemovalListener)1 CountingRemovalListener (com.google.common.cache.TestingRemovalListeners.CountingRemovalListener)1 TestingRemovalListeners.countingRemovalListener (com.google.common.cache.TestingRemovalListeners.countingRemovalListener)1 FakeTicker (com.google.common.testing.FakeTicker)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1