public Map<String, ConcurrentMap> getCaches() { return maps.asMap(); }
/** * Discards any cached principal for the collection of credentials satisfying the given predicate. * * @param predicate a predicate to filter credentials */ public void invalidateAll(Predicate<? super C> predicate) { final Set<C> keys = cache.asMap().keySet().stream() .filter(predicate) .collect(Collectors.toSet()); cache.invalidateAll(keys); }
/** * Discards any cached role associations for principals satisfying * the given predicate. * * @param predicate a predicate to filter credentials */ public void invalidateAll(Predicate<? super P> predicate) { final Set<ImmutablePair<P, String>> keys = cache.asMap().keySet().stream() .filter(cacheKey -> predicate.test(cacheKey.getLeft())) .collect(Collectors.toSet()); cache.invalidateAll(keys); }
/** * Discards any cached role associations for the given principal. * * @param principal */ public void invalidate(P principal) { final Set<ImmutablePair<P, String>> keys = cache.asMap().keySet().stream() .filter(cacheKey -> cacheKey.getLeft().equals(principal)) .collect(Collectors.toSet()); cache.invalidateAll(keys); }
/** * Discards any cached role associations for the given collection * of principals. * * @param principals a list of principals */ public void invalidateAll(Iterable<P> principals) { final Set<P> principalSet = Sets.of(principals); final Set<ImmutablePair<P, String>> keys = cache.asMap().keySet().stream() .filter(cacheKey -> principalSet.contains(cacheKey.getLeft())) .collect(Collectors.toSet()); cache.invalidateAll(keys); }
@Test(dataProvider = "caches") @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 refresh_writerFails(LoadingCache<Integer, Integer> cache, CacheContext context) { Integer key = context.firstKey(); context.clear(); GcFinalization.awaitFullGc(); cache.refresh(key); context.disableRejectingCacheWriter(); assertThat(cache.asMap().isEmpty(), is(false)); }
@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(LoadingCache<Integer, Integer> cache, CacheContext context) { Integer key = context.firstKey(); try { context.clear(); GcFinalization.awaitFullGc(); cache.get(key); } finally { context.disableRejectingCacheWriter(); assertThat(cache.asMap().isEmpty(), is(false)); } }
@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, removalListener = Listener.CONSUMING, writer = Writer.EXCEPTIONAL, compute = Compute.SYNC, loader = {Loader.IDENTITY, Loader.BULK_IDENTITY}) public void getAll_writerFails(LoadingCache<Integer, Integer> cache, CacheContext context) { Set<Integer> keys = context.firstMiddleLastKeys(); try { context.clear(); GcFinalization.awaitFullGc(); cache.getAll(keys); } finally { context.disableRejectingCacheWriter(); assertThat(cache.asMap().isEmpty(), is(false)); } }
@Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, executor = CacheExecutor.THREADED, removalListener = Listener.CONSUMING) public void refresh_conflict(CacheContext context) { AtomicBoolean refresh = new AtomicBoolean(); Integer key = context.absentKey(); Integer original = 1; Integer updated = 2; Integer refreshed = 3; LoadingCache<Integer, Integer> cache = context.build(k -> { await().untilTrue(refresh); return refreshed; }); cache.put(key, original); cache.refresh(key); assertThat(cache.asMap().put(key, updated), is(original)); refresh.set(true); await().until(() -> context.consumedNotifications().size(), is(2)); List<Integer> removed = context.consumedNotifications().stream() .map(RemovalNotification::getValue).collect(toList()); assertThat(cache.getIfPresent(key), is(updated)); assertThat(removed, containsInAnyOrder(original, refreshed)); assertThat(cache, hasRemovalNotifications(context, 2, RemovalCause.REPLACED)); assertThat(context, both(hasLoadSuccessCount(1)).and(hasLoadFailureCount(0))); }
@Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, refreshAfterWrite = Expire.ONE_MINUTE, executor = CacheExecutor.THREADED, removalListener = Listener.CONSUMING) public void put(CacheContext context) { AtomicBoolean refresh = new AtomicBoolean(); Integer key = context.absentKey(); Integer original = 1; Integer updated = 2; Integer refreshed = 3; LoadingCache<Integer, Integer> cache = context.build(k -> { await().untilTrue(refresh); return refreshed; }); cache.put(key, original); context.ticker().advance(2, TimeUnit.MINUTES); assertThat(cache.getIfPresent(key), is(original)); assertThat(cache.asMap().put(key, updated), is(original)); refresh.set(true); await().until(() -> context.consumedNotifications().size(), is(2)); List<Integer> removed = context.consumedNotifications().stream() .map(RemovalNotification::getValue).collect(toList()); assertThat(cache.getIfPresent(key), is(updated)); assertThat(removed, containsInAnyOrder(original, refreshed)); assertThat(cache, hasRemovalNotifications(context, 2, RemovalCause.REPLACED)); assertThat(context, both(hasLoadSuccessCount(1)).and(hasLoadFailureCount(0))); }
@SuppressWarnings("FutureReturnValueIgnored") public Stresser() { ThreadFactory threadFactory = new ThreadFactoryBuilder() .setPriority(Thread.MAX_PRIORITY) .setDaemon(true) .build(); Executors.newSingleThreadScheduledExecutor(threadFactory) .scheduleAtFixedRate(this::status, STATUS_INTERVAL, STATUS_INTERVAL, SECONDS); cache = Caffeine.newBuilder() .maximumSize(operation.maxEntries) .recordStats() .build(key -> key); local = (BoundedLocalCache<Integer, Integer>) cache.asMap(); ints = new Integer[TOTAL_KEYS]; Arrays.setAll(ints, key -> { cache.put(key, key); return key; }); cache.cleanUp(); stopwatch = Stopwatch.createStarted(); status(); }
@Test(dataProvider = "caches") @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 refresh_writerFails(LoadingCache<Integer, Integer> cache, CacheContext context) { context.ticker().advance(1, TimeUnit.HOURS); cache.refresh(context.firstKey()); context.disableRejectingCacheWriter(); context.ticker().advance(-1, TimeUnit.HOURS); assertThat(cache.asMap(), equalTo(context.original())); }
@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(LoadingCache<Integer, Integer> cache, CacheContext context) { try { context.ticker().advance(1, TimeUnit.HOURS); cache.get(context.firstKey()); } finally { context.disableRejectingCacheWriter(); context.ticker().advance(-1, TimeUnit.HOURS); assertThat(cache.asMap(), equalTo(context.original())); } }
@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 getAll_writerFails(LoadingCache<Integer, Integer> cache, CacheContext context) { try { context.ticker().advance(1, TimeUnit.HOURS); cache.getAll(context.firstMiddleLastKeys()); } finally { context.disableRejectingCacheWriter(); context.ticker().advance(-1, TimeUnit.HOURS); assertThat(cache.asMap(), equalTo(context.original())); } }
@CheckNoWriter @Test(dataProvider = "caches") @CacheSpec(loader = Loader.EXCEPTIONAL, executor = CacheExecutor.THREADED, executorFailure = ExecutorFailure.IGNORED) public void get_absent_failure_async(AsyncLoadingCache<Integer, Integer> cache, CacheContext context) throws InterruptedException { AtomicBoolean done = new AtomicBoolean(); Integer key = context.absentKey(); CompletableFuture<Integer> valueFuture = cache.get(key); valueFuture.whenComplete((r, e) -> done.set(true)); Awaits.await().untilTrue(done); Awaits.await().until(() -> !cache.synchronous().asMap().containsKey(context.absentKey())); Awaits.await().until(() -> context, both(hasMissCount(1)).and(hasHitCount(0))); Awaits.await().until(() -> context, both(hasLoadSuccessCount(0)).and(hasLoadFailureCount(1))); assertThat(valueFuture.isCompletedExceptionally(), is(true)); assertThat(cache.getIfPresent(key), is(nullValue())); }
private static void addUnboundedTests(TestSuite suite) throws Exception { suite.addTest(MapTestFactory.suite("UnboundedCache", () -> { Cache<String, String> cache = Caffeine.newBuilder().build(); return cache.asMap(); })); suite.addTest(MapTestFactory.suite("UnboundedAsyncCache", () -> { AsyncLoadingCache<String, String> cache = Caffeine.newBuilder().buildAsync(key -> null); return cache.synchronous().asMap(); })); }
private static void addBoundedTests(TestSuite suite) throws Exception { suite.addTest(MapTestFactory.suite("BoundedCache", () -> { Cache<String, String> cache = Caffeine.newBuilder().maximumSize(Long.MAX_VALUE).build(); return cache.asMap(); })); suite.addTest(MapTestFactory.suite("BoundedAsyncCache", () -> { AsyncLoadingCache<String, String> cache = Caffeine.newBuilder() .maximumSize(Long.MAX_VALUE) .buildAsync(key -> null); return cache.synchronous().asMap(); })); }
if (expirable.hasExpired(millis)) { Expirable<V> expired = expirable; cache.asMap().computeIfPresent(key, (k, e) -> { if (e == expired) { dispatcher.publishExpired(this, key, expired.get());
/** * callers may pass in a Cache object configured appropriately * * @param valueFactory * @param exceptionHandler * @param cacheBuilder - result of Caffeine.newBuilder() + any config (caller may customize the cache) */ public CaffeineConcurrentCache( ValueFactory<K, V, E> valueFactory, ExceptionHandler<E> exceptionHandler, Caffeine<Object, Object> cacheBuilder ) { this.exceptionHandler = exceptionHandler; this.cache = cacheBuilder.build(new CacheValueLoader<>(valueFactory, exceptionHandler)); cacheAsMap = cache.asMap(); }
@Override public int size() { return cache.asMap().size(); }