/** * Creates a new cached authorizer. * * @param metricRegistry the application's registry of metrics * @param authorizer the underlying authorizer * @param builder a {@link CaffeineSpec} */ public CachingAuthorizer( final MetricRegistry metricRegistry, final Authorizer<P> authorizer, final Caffeine<Object, Object> builder) { this.underlying = authorizer; this.cacheMisses = metricRegistry.meter(name(authorizer.getClass(), "cache-misses")); this.getsTimer = metricRegistry.timer(name(authorizer.getClass(), "gets")); this.cache = builder.recordStats().build(key -> { cacheMisses.mark(); return underlying.authorize(key.left, key.right); }); }
/** * Creates a new cached authenticator. * * @param metricRegistry the application's registry of metrics * @param authenticator the underlying authenticator * @param builder a {@link Caffeine} */ public CachingAuthenticator(final MetricRegistry metricRegistry, final Authenticator<C, P> authenticator, final Caffeine<Object, Object> builder) { this.cacheMisses = metricRegistry.meter(name(authenticator.getClass(), "cache-misses")); this.gets = metricRegistry.timer(name(authenticator.getClass(), "gets")); this.cache = builder.recordStats().build(key -> { cacheMisses.mark(); final Optional<P> optPrincipal = authenticator.authenticate(key); if (!optPrincipal.isPresent()) { // Prevent caching of unknown credentials throw new InvalidCredentialsException(); } return optPrincipal; }); }
@Test public void recordStats_twice() { Supplier<StatsCounter> supplier = () -> statsCounter; Runnable[] tasks = { () -> Caffeine.newBuilder().recordStats().recordStats(), () -> Caffeine.newBuilder().recordStats(supplier).recordStats(), () -> Caffeine.newBuilder().recordStats().recordStats(supplier), () -> Caffeine.newBuilder().recordStats(supplier).recordStats(supplier), }; for (Runnable task : tasks) { try { task.run(); Assert.fail(); } catch (IllegalStateException expected) {} } }
private static <T> Cache<PathMappingContext, T> buildCache(String spec) { return Caffeine.from(spec).recordStats().build(); }
@Test(expectedExceptions = NullPointerException.class) public void recordStats_null() { Caffeine.newBuilder().recordStats(null); }
@Test public void recordStats() { Caffeine<?, ?> builder = Caffeine.newBuilder().recordStats(); assertThat(builder.statsCounterSupplier, is(Caffeine.ENABLED_STATS_COUNTER_SUPPLIER)); builder.build(); }
private Caffeine<Object, Object> createCacheBuilder() { return Caffeine.newBuilder().executor(MoreExecutors.directExecutor()).recordStats(); }
@Override public LoadingCache<Object, Object> apply( Caffeine<Object, Object> builder) { return CaffeinatedGuava.build(builder.recordStats(), identityLoader()); } });
@Test public void recordStats_custom() { Supplier<StatsCounter> supplier = () -> statsCounter; Caffeine<?, ?> builder = Caffeine.newBuilder().recordStats(supplier); builder.statsCounterSupplier.get().recordEviction(1); verify(statsCounter).recordEviction(1); builder.build(); }
@Test public void configured() { Caffeine<Object, Object> configured = Caffeine.newBuilder() .initialCapacity(1).weakKeys() .expireAfterAccess(1, TimeUnit.SECONDS).expireAfterWrite(1, TimeUnit.SECONDS) .removalListener((k, v, c) -> {}).recordStats(); assertThat(configured.build(), is(not(nullValue()))); assertThat(configured.buildAsync(), is(not(nullValue()))); assertThat(configured.build(loader), is(not(nullValue()))); assertThat(configured.buildAsync(loader), is(not(nullValue()))); assertThat(configured.refreshAfterWrite(1, TimeUnit.SECONDS).toString(), is(not(Caffeine.newBuilder().toString()))); assertThat(Caffeine.newBuilder().maximumSize(1).toString(), is(not(Caffeine.newBuilder().maximumWeight(1).toString()))); }
public static CaffeineCache create(final CaffeineCacheConfig config, final Executor executor) { Caffeine<Object, Object> builder = Caffeine.newBuilder().recordStats(); if (config.getExpireAfter() >= 0) { builder .expireAfterAccess(config.getExpireAfter(), TimeUnit.MILLISECONDS); } if (config.getSizeInBytes() >= 0) { builder.maximumWeight(config.getSizeInBytes()); } else { builder.maximumWeight(Math.min(MAX_DEFAULT_BYTES, JvmUtils.getRuntimeInfo().getMaxHeapSizeBytes() / 10)); } builder .weigher((NamedKey key, byte[] value) -> value.length + key.key.length + key.namespace.length() * Character.BYTES + FIXED_COST) .executor(executor); return new CaffeineCache(builder.build(), config); }
private static Cache<PathAndEncoding, AggregatedHttpFile> newCache(HttpFileServiceConfig config) { final Caffeine<Object, Object> b = Caffeine.newBuilder(); b.maximumSize(config.maxCacheEntries()) .recordStats() .removalListener((RemovalListener<PathAndEncoding, AggregatedHttpFile>) (key, value, cause) -> { if (value != null) { final HttpData content = value.content(); if (content instanceof ByteBufHolder) { ((ByteBufHolder) content).release(); } } }); return b.build(); }
@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(); }
public void testParse_recordStats() { CaffeineSpec spec = parse("recordStats"); assertTrue(spec.recordStats); assertCaffeineEquivalence(Caffeine.newBuilder().recordStats(), Caffeine.from(spec)); }
public void testBulkLoadInterruptedException() { Exception e = new InterruptedException(); CacheLoader<Object, Object> loader = exceptionLoader(e); LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .recordStats().executor(MoreExecutors.directExecutor()), bulkLoader(loader)); 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 (ExecutionException expected) { assertSame(e, expected.getCause()); } assertTrue(Thread.interrupted()); stats = cache.stats(); assertEquals(1, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(1, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); }
public void testBulkLoadCheckedException() { Exception e = new Exception(); CacheLoader<Object, Object> loader = exceptionLoader(e); LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .recordStats(), bulkLoader(loader)); 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 (ExecutionException expected) { assertSame(e, expected.getCause()); } stats = cache.stats(); assertEquals(1, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(1, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); }
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()); }
public void testBulkLoadUncheckedException() throws ExecutionException { Exception e = new RuntimeException(); CacheLoader<Object, Object> loader = exceptionLoader(e); LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .recordStats(), bulkLoader(loader)); 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 (UncheckedExecutionException expected) { assertSame(e, expected.getCause()); } stats = cache.stats(); assertEquals(1, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(1, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); }
public void testBulkLoadError() throws ExecutionException { Error e = new Error(); CacheLoader<Object, Object> loader = errorLoader(e); LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .recordStats(), bulkLoader(loader)); 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 (ExecutionError expected) { assertSame(e, expected.getCause()); } stats = cache.stats(); assertEquals(1, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(1, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); }
public void testBulkLoadNullMap() throws ExecutionException { LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .recordStats(), new CacheLoader<Object, Object>() { @Override public Object load(Object key) { throw new AssertionError(); } @Override public Map<Object, Object> loadAll(Iterable<? extends Object> keys) { return 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()); }