Search in sources :

Example 1 with RemovalListener

use of com.github.benmanes.caffeine.cache.RemovalListener in project caffeine by ben-manes.

the class Solr10141Test method eviction.

@Test
public void eviction() throws Exception {
    AtomicLong hits = new AtomicLong();
    AtomicLong inserts = new AtomicLong();
    AtomicLong removals = new AtomicLong();
    RemovalListener<Long, Val> listener = (k, v, removalCause) -> {
        assertThat(v.key, is(k));
        if (!v.live.compareAndSet(true, false)) {
            throw new RuntimeException(String.format("listener called more than once! k=%s, v=%s, removalCause=%s", k, v, removalCause));
        }
        removals.incrementAndGet();
    };
    Cache<Long, Val> cache = Caffeine.newBuilder().removalListener(listener).maximumSize(maxEntries).build();
    AtomicLong lastBlock = new AtomicLong();
    AtomicBoolean failed = new AtomicBoolean();
    AtomicLong maxObservedSize = new AtomicLong();
    ConcurrentTestHarness.timeTasks(nThreads, new Runnable() {

        @Override
        public void run() {
            try {
                Random r = new Random(rnd.nextLong());
                for (int i = 0; i < readsPerThread; i++) {
                    test(r);
                }
            } catch (Throwable e) {
                failed.set(true);
                e.printStackTrace();
            }
        }

        void test(Random r) {
            long block = r.nextInt(blocksInTest);
            if (readLastBlockOdds > 0 && r.nextInt(readLastBlockOdds) == 0) {
                // some percent of the time, try to read the last block another
                block = lastBlock.get();
            }
            // thread was just reading/writing
            lastBlock.set(block);
            Long k = block;
            Val v = cache.getIfPresent(k);
            if (v != null) {
                hits.incrementAndGet();
                assertThat(k, is(v.key));
            }
            if ((v == null) || (updateAnyway && r.nextBoolean())) {
                v = new Val();
                v.key = k;
                cache.put(k, v);
                inserts.incrementAndGet();
            }
            long sz = cache.estimatedSize();
            if (sz > maxObservedSize.get()) {
                // race condition here, but an estimate is OK
                maxObservedSize.set(sz);
            }
        }
    });
    await().until(() -> inserts.get() - removals.get() == cache.estimatedSize());
    System.out.printf("Done!%n" + "entries=%,d inserts=%,d removals=%,d hits=%,d maxEntries=%,d maxObservedSize=%,d%n", cache.estimatedSize(), inserts.get(), removals.get(), hits.get(), maxEntries, maxObservedSize.get());
    assertThat(failed.get(), is(false));
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) Awaitility.await(org.awaitility.Awaitility.await) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Matchers.is(org.hamcrest.Matchers.is) Random(java.util.Random) Test(org.testng.annotations.Test) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Cache(com.github.benmanes.caffeine.cache.Cache) RemovalListener(com.github.benmanes.caffeine.cache.RemovalListener) ConcurrentTestHarness(com.github.benmanes.caffeine.testing.ConcurrentTestHarness) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) Random(java.util.Random) AtomicLong(java.util.concurrent.atomic.AtomicLong) Test(org.testng.annotations.Test)

Example 2 with RemovalListener

use of com.github.benmanes.caffeine.cache.RemovalListener in project caffeine by ben-manes.

the class Solr10141Test method clear.

@Test
public void clear() throws Exception {
    AtomicLong inserts = new AtomicLong();
    AtomicLong removals = new AtomicLong();
    AtomicBoolean failed = new AtomicBoolean();
    RemovalListener<Long, Val> listener = (k, v, removalCause) -> {
        assertThat(v.key, is(k));
        if (!v.live.compareAndSet(true, false)) {
            throw new RuntimeException(String.format("listener called more than once! k=%s, v=%s, removalCause=%s", k, v, removalCause));
        }
        removals.incrementAndGet();
    };
    Cache<Long, Val> cache = Caffeine.newBuilder().maximumSize(Integer.MAX_VALUE).removalListener(listener).build();
    ConcurrentTestHarness.timeTasks(nThreads, new Runnable() {

        @Override
        public void run() {
            try {
                Random r = new Random(rnd.nextLong());
                for (int i = 0; i < readsPerThread; i++) {
                    test(r);
                }
            } catch (Throwable e) {
                failed.set(true);
                e.printStackTrace();
            }
        }

        void test(Random r) {
            Long k = (long) r.nextInt(blocksInTest);
            Val v = cache.getIfPresent(k);
            if (v != null) {
                assertThat(k, is(v.key));
            }
            if ((v == null) || (updateAnyway && r.nextBoolean())) {
                v = new Val();
                v.key = k;
                cache.put(k, v);
                inserts.incrementAndGet();
            }
            if (r.nextInt(10) == 0) {
                cache.asMap().clear();
            }
        }
    });
    cache.asMap().clear();
    await().until(() -> inserts.get() == removals.get());
    assertThat(failed.get(), is(false));
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) Awaitility.await(org.awaitility.Awaitility.await) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Matchers.is(org.hamcrest.Matchers.is) Random(java.util.Random) Test(org.testng.annotations.Test) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Cache(com.github.benmanes.caffeine.cache.Cache) RemovalListener(com.github.benmanes.caffeine.cache.RemovalListener) ConcurrentTestHarness(com.github.benmanes.caffeine.testing.ConcurrentTestHarness) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) Random(java.util.Random) AtomicLong(java.util.concurrent.atomic.AtomicLong) Test(org.testng.annotations.Test)

Example 3 with RemovalListener

use of com.github.benmanes.caffeine.cache.RemovalListener 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

RemovalListener (com.github.benmanes.caffeine.cache.RemovalListener)3 Cache (com.github.benmanes.caffeine.cache.Cache)2 Caffeine (com.github.benmanes.caffeine.cache.Caffeine)2 ConcurrentTestHarness (com.github.benmanes.caffeine.testing.ConcurrentTestHarness)2 Random (java.util.Random)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AtomicLong (java.util.concurrent.atomic.AtomicLong)2 Awaitility.await (org.awaitility.Awaitility.await)2 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)2 Matchers.is (org.hamcrest.Matchers.is)2 Test (org.testng.annotations.Test)2 RemovalCause (com.github.benmanes.caffeine.cache.RemovalCause)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