private static <K, V> ConcurrentMap<K, V> map() { return Caffeine.newBuilder() .maximumSize(Integer.MAX_VALUE) .<K, V>build().asMap(); }
RegexStringMatchingStrategy() { patternCache = Caffeine.newBuilder() .expireAfterWrite(1, TimeUnit.HOURS) .build(Pattern::compile); }
@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 MustacheViewRenderer() { this.factories = Caffeine.newBuilder().build(new CacheLoader<Class<? extends View>, MustacheFactory>() { @Override public MustacheFactory load(Class<? extends View> key) throws Exception { return createNewMustacheFactory(key); } }); }
private static <T> Cache<PathMappingContext, T> buildCache(String spec) { return Caffeine.from(spec).recordStats().build(); }
/** * Returns a Caffeine cache wrapped in a Guava {@link Cache} facade. * * @param builder the configured cache builder * @return a cache exposed under the Guava APIs */ @Nonnull public static <K, V, K1 extends K, V1 extends V> Cache<K1, V1> build( @Nonnull Caffeine<K, V> builder) { return new CaffeinatedGuavaCache<>(builder.build()); }
/** * Specifies that each entry should be automatically removed from the cache once a fixed duration * has elapsed after the entry's creation, or the most recent replacement of its value. * <p> * Expired entries may be counted in {@link Cache#estimatedSize()}, but will never be visible to * read or write operations. Expired entries are cleaned up as part of the routine maintenance * described in the class javadoc. * * @param duration the amount of time after an entry is created that it should be automatically * removed * @return this builder instance * @throws IllegalArgumentException if the length of time is negative * @throws IllegalStateException if the time to live or variable expiration was already set */ @Nonnull public Caffeine<K, V> expireAfterWrite(@Nonnull Duration duration) { return expireAfterWrite(duration.toNanos(), TimeUnit.NANOSECONDS); }
/** * Specifies that each entry should be automatically removed from the cache once a fixed duration * has elapsed after the entry's creation, the most recent replacement of its value, or its last * read. Access time is reset by all cache read and write operations (including * {@code Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by operations * on the collection-views of {@link Cache#asMap}. * <p> * Expired entries may be counted in {@link Cache#estimatedSize()}, but will never be visible to * read or write operations. Expired entries are cleaned up as part of the routine maintenance * described in the class javadoc. * * @param duration the amount of time after an entry is created that it should be automatically * removed * @return this builder instance * @throws IllegalArgumentException if the length of time is negative * @throws IllegalStateException if the time to idle or variable expiration was already set */ @Nonnull public Caffeine<K, V> expireAfterAccess(@Nonnull Duration duration) { return expireAfterAccess(duration.toNanos(), TimeUnit.NANOSECONDS); }
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()); } }
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(); }
@Test public void expireAfterAccess_large() { Caffeine<?, ?> builder = Caffeine.newBuilder() .expireAfterAccess(Integer.MAX_VALUE, TimeUnit.NANOSECONDS); assertThat(builder.expireAfterAccessNanos, is((long) Integer.MAX_VALUE)); Expiration<?, ?> expiration = builder.build().policy().expireAfterAccess().get(); assertThat(expiration.getExpiresAfter(TimeUnit.NANOSECONDS), is((long) Integer.MAX_VALUE)); }
public CaffeinePolicy(Config config) { policyStats = new PolicyStats("product.Caffeine"); BasicSettings settings = new BasicSettings(config); maximumSize = settings.maximumSize(); cache = Caffeine.newBuilder() .initialCapacity(maximumSize) .maximumSize(maximumSize) .executor(Runnable::run) .build(); }
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); }
@Test(expectedExceptions = IllegalArgumentException.class) public void maximumSize_negative() { Caffeine.newBuilder().maximumSize(-1); }
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); }
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(""); }
@Test(expectedExceptions = IllegalStateException.class) public void expireAfterWrite_twice() { Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MILLISECONDS) .expireAfterWrite(1, TimeUnit.MILLISECONDS); }
@Test public void recordStats() { Caffeine<?, ?> builder = Caffeine.newBuilder().recordStats(); assertThat(builder.statsCounterSupplier, is(Caffeine.ENABLED_STATS_COUNTER_SUPPLIER)); builder.build(); }
@Test(expectedExceptions = NullPointerException.class) public void recordStats_null() { Caffeine.newBuilder().recordStats(null); }
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(); })); }