Java Code Examples for com.github.benmanes.caffeine.guava.CaffeinatedGuava#build()
The following examples show how to use
com.github.benmanes.caffeine.guava.CaffeinatedGuava#build() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CacheBuilderGwtTest.java From caffeine with Apache License 2.0 | 6 votes |
public void testExpireAfterWrite() { final Cache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .expireAfterWrite(1000, TimeUnit.MILLISECONDS) .executor(MoreExecutors.directExecutor()) .ticker(fakeTicker::read)); cache.put(10, 100); cache.put(20, 200); cache.put(4, 2); fakeTicker.advance(999, TimeUnit.MILLISECONDS); assertEquals(Integer.valueOf(100), cache.getIfPresent(10)); assertEquals(Integer.valueOf(200), cache.getIfPresent(20)); assertEquals(Integer.valueOf(2), cache.getIfPresent(4)); fakeTicker.advance(2, TimeUnit.MILLISECONDS); assertEquals(null, cache.getIfPresent(10)); assertEquals(null, cache.getIfPresent(20)); assertEquals(null, cache.getIfPresent(4)); cache.put(10, 20); assertEquals(Integer.valueOf(20), cache.getIfPresent(10)); fakeTicker.advance(1000, TimeUnit.MILLISECONDS); assertEquals(null, cache.getIfPresent(10)); }
Example 2
Source File: CacheBuilderGwtTest.java From caffeine with Apache License 2.0 | 6 votes |
public void testAsMapEntrySet() { Cache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .expireAfterWrite(1000, TimeUnit.MILLISECONDS) .executor(MoreExecutors.directExecutor()) .ticker(fakeTicker::read)); cache.put(10, 20); fakeTicker.advance(500, TimeUnit.MILLISECONDS); cache.put(20, 22); cache.put(5, 10); fakeTicker.advance(501, TimeUnit.MILLISECONDS); int sum = 0; for (Map.Entry<Integer, Integer> current : cache.asMap().entrySet()) { sum += current.getKey() + current.getValue(); } assertEquals(57, sum); }
Example 3
Source File: CacheBuilderGwtTest.java From caffeine with Apache License 2.0 | 6 votes |
public void testAsMapValues_contains() { Cache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .expireAfterWrite(1000, TimeUnit.MILLISECONDS) .executor(MoreExecutors.directExecutor()) .ticker(fakeTicker::read)); cache.put(10, 20); fakeTicker.advance(500, TimeUnit.MILLISECONDS); cache.put(20, 22); cache.put(5, 10); fakeTicker.advance(501, TimeUnit.MILLISECONDS); assertTrue(cache.asMap().values().contains(22)); assertTrue(cache.asMap().values().contains(10)); assertFalse(cache.asMap().values().contains(20)); }
Example 4
Source File: CacheLoadingTest.java From caffeine with Apache License 2.0 | 6 votes |
/** * On a successful concurrent computation, only one thread does the work, but all the threads get * the same result. */ private static void testConcurrentLoadingDefault(Caffeine<Object, Object> builder) throws InterruptedException { int count = 10; final AtomicInteger callCount = new AtomicInteger(); final CountDownLatch startSignal = new CountDownLatch(count + 1); final Object result = new Object(); LoadingCache<String, Object> cache = CaffeinatedGuava.build(builder, new CacheLoader<String, Object>() { @Override public Object load(String key) { callCount.incrementAndGet(); assertTrue(Uninterruptibles.awaitUninterruptibly(startSignal, 300, TimeUnit.SECONDS)); return result; } }); List<Object> resultArray = doConcurrentGet(cache, "bar", count, startSignal); assertEquals(1, callCount.get()); for (int i = 0; i < count; i++) { assertSame("result(" + i + ") didn't match expected", result, resultArray.get(i)); } }
Example 5
Source File: CacheBuilderGwtTest.java From caffeine with Apache License 2.0 | 6 votes |
public void testAsMapKeySet_contains() { Cache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .expireAfterWrite(1000, TimeUnit.MILLISECONDS) .executor(MoreExecutors.directExecutor()) .ticker(fakeTicker::read)); cache.put(10, 20); fakeTicker.advance(500, TimeUnit.MILLISECONDS); cache.put(20, 22); cache.put(5, 10); fakeTicker.advance(501, TimeUnit.MILLISECONDS); assertTrue(cache.asMap().keySet().contains(20)); assertTrue(cache.asMap().keySet().contains(5)); assertFalse(cache.asMap().keySet().contains(10)); }
Example 6
Source File: CacheEvictionTest.java From caffeine with Apache License 2.0 | 6 votes |
public void testEviction_maxSize() { CountingRemovalListener<Integer, Integer> removalListener = countingRemovalListener(); IdentityLoader<Integer> loader = identityLoader(); LoadingCache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .maximumSize(MAX_SIZE) .executor(MoreExecutors.directExecutor()) .removalListener(removalListener), loader); for (int i = 0; i < 2 * MAX_SIZE; i++) { cache.getUnchecked(i); assertTrue(cache.size() <= MAX_SIZE); } assertEquals(MAX_SIZE, cache.size()); assertEquals(MAX_SIZE, removalListener.getCount()); CacheTesting.checkValidState(cache); }
Example 7
Source File: NullCacheTest.java From caffeine with Apache License 2.0 | 6 votes |
public void testGet_expireAfterWrite() { // Guava sends a notification with SIZE as the removal cause by redefining 0 expiration as // a maximum size of zero. This is not done as expiration can be dynamically updated Object computed = new Object(); LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .executor(MoreExecutors.directExecutor()) .expireAfterWrite(0, SECONDS) .removalListener(listener), constantLoader(computed)); Object key = new Object(); assertSame(computed, cache.getUnchecked(key)); RemovalNotification<Object, Object> notification = listener.remove(); assertSame(key, notification.getKey()); assertSame(computed, notification.getValue()); assertSame(RemovalCause.EXPIRED, notification.getCause()); assertTrue(listener.isEmpty()); checkEmpty(cache); }
Example 8
Source File: CacheLoadingTest.java From caffeine with Apache License 2.0 | 6 votes |
public void testBulkLoadNull() throws ExecutionException { LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .recordStats().executor(MoreExecutors.directExecutor()), bulkLoader(constantLoader(null))); CacheStats stats = cache.stats(); assertEquals(0, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); try { cache.getAll(asList(new Object())); fail(); } catch (InvalidCacheLoadException expected) {} stats = cache.stats(); assertEquals(1, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(1, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); }
Example 9
Source File: CacheBuilderTest.java From caffeine with Apache License 2.0 | 5 votes |
@GwtIncompatible("CacheTesting") public void testNullCache() { CountingRemovalListener<Object, Object> listener = countingRemovalListener(); LoadingCache<Object, Object> nullCache = CaffeinatedGuava.build(Caffeine.newBuilder() .maximumSize(0) .executor(MoreExecutors.directExecutor()) .removalListener(listener), identityLoader()); assertEquals(0, nullCache.size()); Object key = new Object(); assertSame(key, nullCache.getUnchecked(key)); assertEquals(1, listener.getCount()); assertEquals(0, nullCache.size()); CacheTesting.checkEmpty(nullCache.asMap()); }
Example 10
Source File: NullCacheTest.java From caffeine with Apache License 2.0 | 5 votes |
public void testGet_computeNull() { LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .maximumSize(0) .removalListener(listener), constantLoader(null)); try { cache.getUnchecked(new Object()); fail(); } catch (InvalidCacheLoadException e) { /* expected */} assertTrue(listener.isEmpty()); checkEmpty(cache); }
Example 11
Source File: CacheBuilderTest.java From caffeine with Apache License 2.0 | 5 votes |
public void testTimeToIdleAndToLive() { CaffeinatedGuava.build(Caffeine.newBuilder() .expireAfterWrite(1, NANOSECONDS) .expireAfterAccess(1, NANOSECONDS), identityLoader()); // well, it didn't blow up. }
Example 12
Source File: CacheLoadingTest.java From caffeine with Apache License 2.0 | 5 votes |
/** * On a concurrent computation that returns null, all threads should get an * InvalidCacheLoadException, with the loader only called once. The result should not be cached * (a later request should call the loader again). */ private static void testConcurrentLoadingNull(Caffeine<Object, Object> builder) throws InterruptedException { int count = 10; final AtomicInteger callCount = new AtomicInteger(); final CountDownLatch startSignal = new CountDownLatch(count + 1); LoadingCache<String, String> cache = CaffeinatedGuava.build(builder, new CacheLoader<String, String>() { @Override public String load(String key) { callCount.incrementAndGet(); assertTrue(Uninterruptibles.awaitUninterruptibly(startSignal, 300, TimeUnit.SECONDS)); return null; } }); List<Object> result = doConcurrentGet(cache, "bar", count, startSignal); assertEquals(count, callCount.get()); for (int i = 0; i < count; i++) { assertTrue(result.get(i) instanceof InvalidCacheLoadException); } // subsequent calls should call the loader again, not get the old exception try { cache.getUnchecked("bar"); fail(); } catch (InvalidCacheLoadException expected) { } assertEquals(count + 1, callCount.get()); }
Example 13
Source File: CacheBuilderGwtTest.java From caffeine with Apache License 2.0 | 5 votes |
public void testAsMapValues_iteratorRemove() { Cache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .expireAfterWrite(1000, TimeUnit.MILLISECONDS) .executor(MoreExecutors.directExecutor()) .ticker(fakeTicker::read)); cache.put(10, 20); Iterator<Integer> iterator = cache.asMap().values().iterator(); iterator.next(); iterator.remove(); assertEquals(0, cache.size()); }
Example 14
Source File: CacheExpirationTest.java From caffeine with Apache License 2.0 | 5 votes |
public void testExpiringGet_expireAfterWrite() { FakeTicker ticker = new FakeTicker(); CountingRemovalListener<String, Integer> removalListener = countingRemovalListener(); WatchedCreatorLoader loader = new WatchedCreatorLoader(); LoadingCache<String, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .expireAfterWrite(EXPIRING_TIME, MILLISECONDS) .executor(MoreExecutors.directExecutor()) .removalListener(removalListener) .ticker(ticker::read), loader); runExpirationTest(cache, loader, ticker, removalListener); }
Example 15
Source File: CacheEvictionTest.java From caffeine with Apache License 2.0 | 5 votes |
public void testEviction_maxWeightOneSegment() { IdentityLoader<Integer> loader = identityLoader(); LoadingCache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .executor(MoreExecutors.directExecutor()) .maximumWeight(2 * MAX_SIZE) .weigher(constantWeigher(2)), loader); for (int i = 0; i < 2 * MAX_SIZE; i++) { cache.getUnchecked(i); assertEquals(Math.min(i + 1, MAX_SIZE), cache.size()); } assertEquals(MAX_SIZE, cache.size()); CacheTesting.checkValidState(cache); }
Example 16
Source File: LocalCacheMapComputeTest.java From caffeine with Apache License 2.0 | 5 votes |
public void testComputeIfAbsentEviction() { Cache<String, String> c = CaffeinatedGuava.build( Caffeine.newBuilder().executor(MoreExecutors.directExecutor()).maximumSize(1)); assertThat(c.asMap().computeIfAbsent("hash-1", k -> "")).isEqualTo(""); assertThat(c.asMap().computeIfAbsent("hash-1", k -> "")).isEqualTo(""); assertThat(c.asMap().computeIfAbsent("hash-1", k -> "")).isEqualTo(""); assertThat(c.size()).isEqualTo(1); assertThat(c.asMap().computeIfAbsent("hash-2", k -> "")).isEqualTo(""); }
Example 17
Source File: CacheBuilderTest.java From caffeine with Apache License 2.0 | 4 votes |
/** * Calls get() repeatedly from many different threads, and tests that all of the removed entries * (removed because of size limits or expiration) trigger appropriate removal notifications. */ @GwtIncompatible("QueuingRemovalListener") @SuppressWarnings("FutureReturnValueIgnored") // FIXME(ben): disabled due to TravisCI killing the process public void testRemovalNotification_get_basher() throws InterruptedException { int nTasks = 1000; int nThreads = 100; final int getsPerTask = 1000; final int nUniqueKeys = 10000; final Random random = new Random(); // Randoms.insecureRandom(); QueuingRemovalListener<String, String> removalListener = queuingRemovalListener(); final AtomicInteger computeCount = new AtomicInteger(); final AtomicInteger exceptionCount = new AtomicInteger(); final AtomicInteger computeNullCount = new AtomicInteger(); CacheLoader<String, String> countingIdentityLoader = new CacheLoader<String, String>() { @Override public String load(String key) { int behavior = random.nextInt(4); if (behavior == 0) { // throw an exception exceptionCount.incrementAndGet(); throw new RuntimeException("fake exception for test"); } else if (behavior == 1) { // return null computeNullCount.incrementAndGet(); return null; } else if (behavior == 2) { // slight delay before returning Uninterruptibles.sleepUninterruptibly(5, TimeUnit.MILLISECONDS); computeCount.incrementAndGet(); return key; } else { computeCount.incrementAndGet(); return key; } } }; final LoadingCache<String, String> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .recordStats() .executor(MoreExecutors.directExecutor()) .expireAfterWrite(100, TimeUnit.MILLISECONDS) .removalListener(removalListener) //.maximumSize(5000) , countingIdentityLoader); ExecutorService threadPool = Executors.newFixedThreadPool(nThreads); for (int i = 0; i < nTasks; i++) { threadPool.submit(new Runnable() { @Override public void run() { for (int j = 0; j < getsPerTask; j++) { try { cache.getUnchecked("key" + random.nextInt(nUniqueKeys)); } catch (RuntimeException e) { } } } }); } threadPool.shutdown(); assertTrue(threadPool.awaitTermination(300, TimeUnit.SECONDS)); // Since we're not doing any more cache operations, and the cache only expires/evicts when doing // other operations, the cache and the removal queue won't change from this point on. // Verify that each received removal notification was valid for (RemovalNotification<String, String> notification : removalListener) { assertEquals("Invalid removal notification", notification.getKey(), notification.getValue()); } CacheStats stats = cache.stats(); assertEquals(removalListener.size(), stats.evictionCount()); assertEquals(computeCount.get(), stats.loadSuccessCount()); assertEquals(exceptionCount.get() + computeNullCount.get(), stats.loadExceptionCount()); // each computed value is still in the cache, or was passed to the removal listener assertEquals(computeCount.get(), cache.size() + removalListener.size()); }
Example 18
Source File: CacheLoadingTest.java From caffeine with Apache License 2.0 | 4 votes |
public void testBulkLoad_loadAll() throws ExecutionException { IdentityLoader<Integer> backingLoader = identityLoader(); LoadingCache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .recordStats().executor(MoreExecutors.directExecutor()), bulkLoader(backingLoader)); CacheStats stats = cache.stats(); assertEquals(0, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); assertEquals(ImmutableMap.of(), cache.getAll(ImmutableList.<Integer>of())); assertEquals(0, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); assertEquals(ImmutableMap.of(1, 1), cache.getAll(asList(1))); stats = cache.stats(); assertEquals(1, stats.missCount()); assertEquals(1, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); assertEquals(ImmutableMap.of(1, 1, 2, 2, 3, 3, 4, 4), cache.getAll(asList(1, 2, 3, 4))); stats = cache.stats(); assertEquals(4, stats.missCount()); assertEquals(2, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(1, stats.hitCount()); assertEquals(ImmutableMap.of(2, 2, 3, 3), cache.getAll(asList(2, 3))); stats = cache.stats(); assertEquals(4, stats.missCount()); assertEquals(2, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(3, stats.hitCount()); // duplicate keys are ignored, and don't impact stats assertEquals(ImmutableMap.of(4, 4, 5, 5), cache.getAll(asList(4, 5))); stats = cache.stats(); assertEquals(5, stats.missCount()); assertEquals(3, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(4, stats.hitCount()); }
Example 19
Source File: CacheLoadingTest.java From caffeine with Apache License 2.0 | 4 votes |
public void testBulkLoad_default() throws ExecutionException { LoadingCache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .recordStats(), TestingCacheLoaders.<Integer>identityLoader()); CacheStats stats = cache.stats(); assertEquals(0, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); assertEquals(ImmutableMap.of(), cache.getAll(ImmutableList.<Integer>of())); assertEquals(0, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); assertEquals(ImmutableMap.of(1, 1), cache.getAll(asList(1))); stats = cache.stats(); assertEquals(1, stats.missCount()); assertEquals(1, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); assertEquals(ImmutableMap.of(1, 1, 2, 2, 3, 3, 4, 4), cache.getAll(asList(1, 2, 3, 4))); stats = cache.stats(); assertEquals(4, stats.missCount()); assertEquals(4, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(1, stats.hitCount()); assertEquals(ImmutableMap.of(2, 2, 3, 3), cache.getAll(asList(2, 3))); stats = cache.stats(); assertEquals(4, stats.missCount()); assertEquals(4, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(3, stats.hitCount()); // duplicate keys are ignored, and don't impact stats assertEquals(ImmutableMap.of(4, 4, 5, 5), cache.getAll(asList(4, 5))); stats = cache.stats(); assertEquals(5, stats.missCount()); assertEquals(5, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(4, stats.hitCount()); }
Example 20
Source File: CacheManualTest.java From caffeine with Apache License 2.0 | 4 votes |
public void testGetIfPresent() { Cache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder().recordStats()); CacheStats stats = cache.stats(); assertEquals(0, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); Object one = new Object(); Object two = new Object(); assertNull(cache.getIfPresent(one)); stats = cache.stats(); assertEquals(1, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); assertNull(cache.asMap().get(one)); assertFalse(cache.asMap().containsKey(one)); assertFalse(cache.asMap().containsValue(two)); assertNull(cache.getIfPresent(two)); stats = cache.stats(); assertEquals(2, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); assertNull(cache.asMap().get(two)); assertFalse(cache.asMap().containsKey(two)); assertFalse(cache.asMap().containsValue(one)); cache.put(one, two); assertSame(two, cache.getIfPresent(one)); stats = cache.stats(); assertEquals(2, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(1, stats.hitCount()); assertSame(two, cache.asMap().get(one)); assertTrue(cache.asMap().containsKey(one)); assertTrue(cache.asMap().containsValue(two)); assertNull(cache.getIfPresent(two)); stats = cache.stats(); assertEquals(3, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(1, stats.hitCount()); assertNull(cache.asMap().get(two)); assertFalse(cache.asMap().containsKey(two)); assertFalse(cache.asMap().containsValue(one)); cache.put(two, one); assertSame(two, cache.getIfPresent(one)); stats = cache.stats(); assertEquals(3, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(2, stats.hitCount()); assertSame(two, cache.asMap().get(one)); assertTrue(cache.asMap().containsKey(one)); assertTrue(cache.asMap().containsValue(two)); assertSame(one, cache.getIfPresent(two)); stats = cache.stats(); assertEquals(3, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(3, stats.hitCount()); assertSame(one, cache.asMap().get(two)); assertTrue(cache.asMap().containsKey(two)); assertTrue(cache.asMap().containsValue(one)); }