@Override @Nullable public ValueWrapper putIfAbsent(Object key, @Nullable final Object value) { PutIfAbsentFunction callable = new PutIfAbsentFunction(value); Object result = this.cache.get(key, callable); return (callable.called ? null : toValueWrapper(result)); }
@Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, expiryTime = Expire.ONE_MINUTE, mustExpireWithAnyOf = { AFTER_WRITE, VARIABLE }, expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE }, expireAfterWrite = {Expire.DISABLED, Expire.ONE_MINUTE}) public void get_writeTime(Cache<Integer, Integer> cache, CacheContext context) { Integer key = context.absentKey(); Integer value = context.absentValue(); cache.get(key, k -> { context.ticker().advance(5, TimeUnit.MINUTES); return value; }); assertThat(cache.estimatedSize(), is(1L)); assertThat(cache.getIfPresent(key), is(value)); }
@SuppressWarnings("unchecked") @Override @Nullable public <T> T get(Object key, final Callable<T> valueLoader) { return (T) fromStoreValue(this.cache.get(key, new LoadFunction(valueLoader))); }
public <T> SimpleStreamProxyObject<T> getSubscriber(final SimpleStream streamActorRef) { //noinspection unchecked return weakCache.get(streamActorRef, o -> new SimpleStreamProxyObject<T>(this, streamActorRef)); }
@Override @Nullable public ValueWrapper putIfAbsent(Object key, @Nullable final Object value) { PutIfAbsentFunction callable = new PutIfAbsentFunction(value); Object result = this.cache.get(key, callable); return (callable.called ? null : toValueWrapper(result)); }
@SuppressWarnings("unchecked") @Override @Nullable public <T> T get(Object key, final Callable<T> valueLoader) { return (T) fromStoreValue(this.cache.get(key, new LoadFunction(valueLoader))); }
private HttpFile cache(ServiceRequestContext ctx, PathAndEncoding pathAndEncoding, HttpFile file) { assert cache != null; // TODO(trustin): We assume here that the file being read is small enough that it will not block // an event loop for a long time. Revisit if the assumption turns out to be false. final AggregatedHttpFile cachedFile = cache.get(pathAndEncoding, key -> { try { return file.aggregateWithPooledObjects(MoreExecutors.directExecutor(), ctx.alloc()).get(); } catch (Exception e) { logger.warn("{} Failed to cache a file: {}", ctx, file, Exceptions.peel(e)); return null; } }); return cachedFile != null ? cachedFile : file; }
@CacheSpec @CheckNoWriter @CheckNoStats @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void get_nullKey(Cache<Integer, Integer> cache, CacheContext context) { cache.get(null, Function.identity()); }
@CacheSpec @CheckNoWriter @CheckNoStats @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void get_nullKeyAndLoader(Cache<Integer, Integer> cache, CacheContext context) { cache.get(null, null); }
@CheckNoWriter @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }) public void get_present(Cache<Integer, Integer> cache, CacheContext context) { Function<Integer, Integer> loader = key -> { throw new RuntimeException(); }; assertThat(cache.get(context.firstKey(), loader), is(context.original().get(context.firstKey()))); assertThat(cache.get(context.middleKey(), loader), is(context.original().get(context.middleKey()))); assertThat(cache.get(context.lastKey(), loader), is(context.original().get(context.lastKey()))); assertThat(context, both(hasMissCount(0)).and(hasHitCount(3))); assertThat(context, both(hasLoadSuccessCount(0)).and(hasLoadFailureCount(0))); }
@Test(dataProvider = "caches", expectedExceptions = DeleteException.class) @CacheSpec(keys = ReferenceType.STRONG, values = {ReferenceType.WEAK, ReferenceType.SOFT}, implementation = Implementation.Caffeine, expireAfterAccess = Expire.DISABLED, expireAfterWrite = Expire.DISABLED, maximumSize = Maximum.DISABLED, weigher = CacheWeigher.DEFAULT, population = Population.FULL, stats = Stats.ENABLED, compute = Compute.SYNC, removalListener = Listener.CONSUMING, writer = Writer.EXCEPTIONAL) public void get_writerFails(Cache<Integer, Integer> cache, CacheContext context) { Integer key = context.firstKey(); try { context.clear(); GcFinalization.awaitFullGc(); cache.get(key, Function.identity()); } finally { context.disableRejectingCacheWriter(); assertThat(cache.asMap().isEmpty(), is(false)); } }
@CacheSpec @CheckNoWriter @CheckNoStats @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void get_nullLoader(Cache<Integer, Integer> cache, CacheContext context) { cache.get(context.absentKey(), null); }
@CacheSpec(implementation = Implementation.Caffeine, population = Population.FULL, expiry = CacheExpiry.MOCKITO) @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void get_expiryFails_read(Cache<Integer, Integer> cache, CacheContext context) { try { context.ticker().advance(1, TimeUnit.HOURS); when(context.expiry().expireAfterRead(any(), any(), anyLong(), anyLong())) .thenThrow(ExpirationException.class); cache.get(context.firstKey(), identity()); } finally { context.ticker().advance(-1, TimeUnit.HOURS); assertThat(cache.asMap(), equalTo(context.original())); } }
@CacheSpec(implementation = Implementation.Caffeine, population = Population.FULL, expiry = CacheExpiry.MOCKITO, writer = Writer.MOCKITO, removalListener = Listener.REJECTING) @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void get_expiryFails_create(Cache<Integer, Integer> cache, CacheContext context) { try { context.ticker().advance(1, TimeUnit.HOURS); when(context.expiry().expireAfterCreate(any(), any(), anyLong())) .thenThrow(ExpirationException.class); cache.get(context.absentKey(), identity()); } finally { context.ticker().advance(-1, TimeUnit.HOURS); assertThat(cache.asMap(), equalTo(context.original())); verify(context.cacheWriter(), never()).write(anyInt(), anyInt()); } }
@Test(dataProvider = "caches") @CacheSpec(mustExpireWithAnyOf = { AFTER_ACCESS, VARIABLE }, expiry = { CacheExpiry.DISABLED, CacheExpiry.ACCESS }, expiryTime = Expire.ONE_MINUTE, expireAfterAccess = Expire.ONE_MINUTE, population = { Population.PARTIAL, Population.FULL }) public void get(Cache<Integer, Integer> cache, CacheContext context) { Function<Integer, Integer> mappingFunction = context.original()::get; context.ticker().advance(30, TimeUnit.SECONDS); cache.get(context.firstKey(), mappingFunction); context.ticker().advance(45, TimeUnit.SECONDS); cache.get(context.firstKey(), mappingFunction); cache.get(context.lastKey(), mappingFunction); // recreated cache.cleanUp(); assertThat(cache.estimatedSize(), is(2L)); long count = context.initialSize() - 1; assertThat(cache, hasRemovalNotifications(context, count, RemovalCause.EXPIRED)); verifyWriter(context, (verifier, writer) -> verifier.deletions(count, RemovalCause.EXPIRED)); }
@Test(dataProvider = "caches") @CacheSpec(keys = ReferenceType.STRONG, values = {ReferenceType.WEAK, ReferenceType.SOFT}, expireAfterAccess = Expire.DISABLED, expireAfterWrite = Expire.DISABLED, maximumSize = Maximum.DISABLED, weigher = CacheWeigher.DEFAULT, population = Population.FULL, stats = Stats.ENABLED, removalListener = Listener.CONSUMING) public void get(Cache<Integer, Integer> cache, CacheContext context) { Integer key = context.firstKey(); context.clear(); GcFinalization.awaitFullGc(); assertThat(cache.get(key, k -> context.absentValue()), is(context.absentValue())); long count = context.initialSize() - cache.estimatedSize() + 1; if (context.population() != Population.SINGLETON) { assertThat(count, is(greaterThan(1L))); } assertThat(cache, hasRemovalNotifications(context, count, RemovalCause.COLLECTED)); verifyWriter(context, (verifier, writer) -> verifier.deletions(count, RemovalCause.COLLECTED)); }
@CacheSpec @CheckNoWriter @Test(dataProvider = "caches") public void get_absent(Cache<Integer, Integer> cache, CacheContext context) { Integer key = context.absentKey(); Integer value = cache.get(key, k -> context.absentValue()); assertThat(value, is(context.absentValue())); assertThat(context, both(hasMissCount(1)).and(hasHitCount(0))); assertThat(context, both(hasLoadSuccessCount(1)).and(hasLoadFailureCount(0))); }
@CacheSpec @CheckNoWriter @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void get_throwsException(Cache<Integer, Integer> cache, CacheContext context) { try { cache.get(context.absentKey(), key -> { throw new IllegalStateException(); }); } finally { assertThat(context, both(hasMissCount(1)).and(hasHitCount(0))); assertThat(context, both(hasLoadSuccessCount(0)).and(hasLoadFailureCount(1))); } }
@Test(dataProvider = "caches") @CacheSpec(population = { Population.PARTIAL, Population.FULL }, mustExpireWithAnyOf = { AFTER_WRITE, VARIABLE }, expireAfterWrite = Expire.ONE_MINUTE, expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE }, expiryTime = Expire.ONE_MINUTE) public void get(Cache<Integer, Integer> cache, CacheContext context) { Function<Integer, Integer> mappingFunction = context.original()::get; context.ticker().advance(30, TimeUnit.SECONDS); cache.get(context.firstKey(), mappingFunction); context.ticker().advance(45, TimeUnit.SECONDS); cache.get(context.lastKey(), mappingFunction); // recreated cache.cleanUp(); assertThat(cache.estimatedSize(), is(1L)); long count = context.initialSize(); assertThat(cache, hasRemovalNotifications(context, count, RemovalCause.EXPIRED)); verifyWriter(context, (verifier, writer) -> verifier.deletions(count, RemovalCause.EXPIRED)); }
@Test(dataProvider = "caches", expectedExceptions = DeleteException.class) @CacheSpec(implementation = Implementation.Caffeine, keys = ReferenceType.STRONG, population = Population.FULL, expiryTime = Expire.ONE_MINUTE, mustExpireWithAnyOf = { AFTER_ACCESS, AFTER_WRITE, VARIABLE }, expiry = { CacheExpiry.DISABLED, CacheExpiry.CREATE, CacheExpiry.WRITE, CacheExpiry.ACCESS }, expireAfterAccess = {Expire.DISABLED, Expire.ONE_MINUTE}, expireAfterWrite = {Expire.DISABLED, Expire.ONE_MINUTE}, compute = Compute.SYNC, writer = Writer.EXCEPTIONAL, removalListener = Listener.REJECTING) public void get_writerFails(Cache<Integer, Integer> cache, CacheContext context) { try { context.ticker().advance(1, TimeUnit.HOURS); cache.get(context.firstKey(), Function.identity()); } finally { context.disableRejectingCacheWriter(); context.ticker().advance(-1, TimeUnit.HOURS); assertThat(cache.asMap(), equalTo(context.original())); } }