com.github.benmanes.caffeine.cache.Caffeine Java Examples
The following examples show how to use
com.github.benmanes.caffeine.cache.Caffeine.
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: NullCacheTest.java From caffeine with Apache License 2.0 | 6 votes |
public void testGet_runtimeException() { final RuntimeException e = new RuntimeException(); LoadingCache<Object, Object> map = CaffeinatedGuava.build(Caffeine.newBuilder() .maximumSize(0) .removalListener(listener), exceptionLoader(e)); try { map.getUnchecked(new Object()); fail(); } catch (UncheckedExecutionException uee) { assertSame(e, uee.getCause()); } assertTrue(listener.isEmpty()); checkEmpty(map); }
Example #2
Source File: GenericEnrichmentBolt.java From metron with Apache License 2.0 | 6 votes |
@Override public void prepare(Map conf, TopologyContext topologyContext, OutputCollector collector) { super.prepare(conf, topologyContext, collector); this.collector = collector; if (this.maxCacheSize == null) throw new IllegalStateException("MAX_CACHE_SIZE_OBJECTS_NUM must be specified"); if (this.maxTimeRetain == null) throw new IllegalStateException("MAX_TIME_RETAIN_MINUTES must be specified"); if (this.adapter == null) throw new IllegalStateException("Adapter must be specified"); loader = key -> adapter.enrich(key); cache = Caffeine.newBuilder().maximumSize(maxCacheSize) .expireAfterWrite(maxTimeRetain, TimeUnit.MINUTES) .build(loader); boolean success = adapter.initializeAdapter(getConfigurations().getGlobalConfig()); if (!success) { LOG.error("[Metron] GenericEnrichmentBolt could not initialize adapter"); throw new IllegalStateException("Could not initialize adapter..."); } perfLog = new PerformanceLogger(() -> getConfigurations().getGlobalConfig(), GenericEnrichmentBolt.Perf.class.getName()); initializeStellar(); }
Example #3
Source File: CacheLoadingTest.java From caffeine with Apache License 2.0 | 6 votes |
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()); }
Example #4
Source File: CacheEvictionTest.java From caffeine with Apache License 2.0 | 6 votes |
public void testEviction_overweight() { // test weighted lru within a single segment IdentityLoader<Integer> loader = identityLoader(); LoadingCache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .executor(MoreExecutors.directExecutor()) .maximumWeight(45) .weigher(intKeyWeigher()), loader); CacheTesting.warmUp(cache, 0, 10); Set<Integer> keySet = cache.asMap().keySet(); assertThat(keySet).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); // add an at-the-maximum-weight entry getAll(cache, asList(45)); CacheTesting.drainRecencyQueues(cache); assertThat(keySet).containsExactly(0, 45); // add an over-the-maximum-weight entry getAll(cache, asList(46)); CacheTesting.drainRecencyQueues(cache); assertThat(keySet).contains(0); }
Example #5
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 #6
Source File: CacheBuilderGwtTest.java From caffeine with Apache License 2.0 | 6 votes |
public void testAsMap_containsKey() { Cache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .expireAfterWrite(20000, TimeUnit.MILLISECONDS) .executor(MoreExecutors.directExecutor()) .ticker(fakeTicker::read)); cache.put(654, 2675); fakeTicker.advance(10000, TimeUnit.MILLISECONDS); cache.put(2456, 56); cache.put(2, 15); fakeTicker.advance(10001, TimeUnit.MILLISECONDS); assertTrue(cache.asMap().containsKey(2)); assertTrue(cache.asMap().containsKey(2456)); assertFalse(cache.asMap().containsKey(654)); }
Example #7
Source File: ConditionalLogger.java From prebid-server-java with Apache License 2.0 | 6 votes |
public ConditionalLogger(String key, Logger logger) { this.key = key; // can be null this.logger = Objects.requireNonNull(logger); messageToCount = Caffeine.newBuilder() .maximumSize(CACHE_MAXIMUM_SIZE) .expireAfterWrite(EXPIRE_CACHE_DURATION, TimeUnit.HOURS) .<String, AtomicInteger>build() .asMap(); messageToWait = Caffeine.newBuilder() .maximumSize(CACHE_MAXIMUM_SIZE) .expireAfterWrite(EXPIRE_CACHE_DURATION, TimeUnit.HOURS) .<String, Long>build() .asMap(); }
Example #8
Source File: RepositoryCache.java From centraldogma with Apache License 2.0 | 6 votes |
@SuppressWarnings({ "rawtypes", "unchecked" }) public RepositoryCache(String cacheSpec, MeterRegistry meterRegistry) { this.cacheSpec = requireNonNull(validateCacheSpec(cacheSpec), "cacheSpec"); requireNonNull(meterRegistry, "meterRegistry"); final Caffeine<Object, Object> builder = Caffeine.from(cacheSpec); if (cacheSpec.contains("maximumWeight=")) { builder.weigher((Weigher<CacheableCall, Object>) CacheableCall::weigh); } cache = builder.recordStats() .buildAsync((key, executor) -> { logger.debug("Cache miss: {}", key); return key.execute(); }); CaffeineCacheMetrics.monitor(meterRegistry, cache, "repository"); }
Example #9
Source File: CacheBuilderGwtTest.java From caffeine with Apache License 2.0 | 6 votes |
public void testLoader() throws ExecutionException { final Cache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder()); Callable<Integer> loader = new Callable<Integer>() { private int i = 0; @Override public Integer call() throws Exception { return ++i; } }; cache.put(0, 10); assertEquals(Integer.valueOf(10), cache.get(0, loader)); assertEquals(Integer.valueOf(1), cache.get(20, loader)); assertEquals(Integer.valueOf(2), cache.get(34, loader)); cache.invalidate(0); assertEquals(Integer.valueOf(3), cache.get(0, loader)); cache.put(0, 10); cache.invalidateAll(); assertEquals(Integer.valueOf(4), cache.get(0, loader)); }
Example #10
Source File: AgentConfigurationServiceImpl.java From genie with Apache License 2.0 | 6 votes |
/** * Constructor. * * @param agentConfigurationProperties the properties * @param environment the environment */ public AgentConfigurationServiceImpl( final AgentConfigurationProperties agentConfigurationProperties, final Environment environment ) { this.agentConfigurationProperties = agentConfigurationProperties; this.environment = environment; this.agentPropertiesPattern = Pattern.compile( this.agentConfigurationProperties.getAgentPropertiesFilterPattern(), Pattern.CASE_INSENSITIVE ); // Use a cache to re-compute agent properties periodically, rather than for every request. this.cache = Caffeine .newBuilder() .expireAfterWrite(this.agentConfigurationProperties.getCacheExpirationInterval()) .refreshAfterWrite(this.agentConfigurationProperties.getCacheRefreshInterval()) .initialCapacity(1) .build(this::loadProperties); }
Example #11
Source File: BlockDirectoryCache.java From lucene-solr with Apache License 2.0 | 6 votes |
public BlockDirectoryCache(BlockCache blockCache, String path, Metrics metrics, boolean releaseBlocks) { this.blockCache = blockCache; this.path = path; this.metrics = metrics; names = Caffeine.newBuilder().maximumSize(50000).build(); if (releaseBlocks) { keysToRelease = Collections.newSetFromMap(new ConcurrentHashMap<BlockCacheKey,Boolean>(1024, 0.75f, 512)); blockCache.setOnRelease(new OnRelease() { @Override public void release(BlockCacheKey key) { keysToRelease.remove(key); } }); } }
Example #12
Source File: MetricsStatsCounterTest.java From caffeine with Apache License 2.0 | 6 votes |
@Test public void metrics() { // Use a registry that is exported using a Reporter (via console, JMX, Graphite, etc) MetricRegistry registry = new MetricRegistry(); // Create the cache with a dedicated, uniquely named stats counter LoadingCache<Integer, Integer> cache = Caffeine.newBuilder() .recordStats(() -> new MetricsStatsCounter(registry, "example")) .build(key -> key); // Perform application work for (int i = 0; i < 4; i++) { cache.get(1); } // Statistics can be queried and reported on assertThat(cache.stats().hitCount(), is(3L)); assertThat(registry.counter("example.hits").getCount(), is(3L)); }
Example #13
Source File: CaffeineProvider.java From J2Cache with Apache License 2.0 | 6 votes |
/** * 返回对 Caffeine cache 的 封装 * @param region region name * @param size max cache object size in memory * @param expire cache object expire time in millisecond * if this parameter set to 0 or negative numbers * means never expire * @param listener j2cache cache listener * @return CaffeineCache */ private CaffeineCache newCaffeineCache(String region, long size, long expire, CacheExpiredListener listener) { Caffeine<Object, Object> caffeine = Caffeine.newBuilder(); caffeine = caffeine.maximumSize(size) .removalListener((k,v, cause) -> { /* * 程序删除的缓存不做通知处理,因为上层已经做了处理 * 当缓存数据不是因为手工删除和超出容量限制而被删除的情况,就需要通知上层侦听器 */ if(cause != RemovalCause.EXPLICIT && cause != RemovalCause.REPLACED && cause != RemovalCause.SIZE) listener.notifyElementExpired(region, (String)k); }); if (expire > 0) { caffeine = caffeine.expireAfterWrite(expire, TimeUnit.SECONDS); } com.github.benmanes.caffeine.cache.Cache<String, Object> loadingCache = caffeine.build(); return new CaffeineCache(loadingCache, size, expire); }
Example #14
Source File: CacheBuilderGwtTest.java From caffeine with Apache License 2.0 | 6 votes |
public void testInvalidateAll() { Cache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder()); cache.put(654, 2675); cache.put(2456, 56); cache.put(2, 15); cache.invalidateAll(); assertFalse(cache.asMap().containsKey(654)); assertFalse(cache.asMap().containsKey(2456)); assertFalse(cache.asMap().containsKey(2)); cache.put(654, 2675); cache.put(2456, 56); cache.put(2, 15); cache.put(1, 3); cache.invalidateAll(ImmutableSet.of(1, 2)); assertFalse(cache.asMap().containsKey(1)); assertFalse(cache.asMap().containsKey(2)); assertTrue(cache.asMap().containsKey(654)); assertTrue(cache.asMap().containsKey(2456)); }
Example #15
Source File: NullCacheTest.java From caffeine with Apache License 2.0 | 6 votes |
public void testGet_expireAfterAccess() { // 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()) .expireAfterAccess(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 #16
Source File: CachingSchemaRegistryClient.java From nifi with Apache License 2.0 | 6 votes |
public CachingSchemaRegistryClient(final SchemaRegistryClient toWrap, final int cacheSize, final long expirationNanos) { this.client = toWrap; nameCache = Caffeine.newBuilder() .maximumSize(cacheSize) .expireAfterWrite(Duration.ofNanos(expirationNanos)) .build(client::getSchema); nameVersionCache = Caffeine.newBuilder() .maximumSize(cacheSize) .expireAfterWrite(Duration.ofNanos(expirationNanos)) .build(key -> client.getSchema(key.getLeft(), key.getRight())); idCache = Caffeine.newBuilder() .maximumSize(cacheSize) .expireAfterWrite(Duration.ofNanos(expirationNanos)) .build(client::getSchema); }
Example #17
Source File: LocalCacheMapComputeTest.java From caffeine with Apache License 2.0 | 5 votes |
public void testComputeEviction() { Cache<String, String> c = CaffeinatedGuava.build( Caffeine.newBuilder().executor(MoreExecutors.directExecutor()).maximumSize(1)); assertThat(c.asMap().compute("hash-1", (k, v) -> "a")).isEqualTo("a"); assertThat(c.asMap().compute("hash-1", (k, v) -> "b")).isEqualTo("b"); assertThat(c.asMap().compute("hash-1", (k, v) -> "c")).isEqualTo("c"); assertThat(c.size()).isEqualTo(1); assertThat(c.asMap().computeIfAbsent("hash-2", k -> "")).isEqualTo(""); }
Example #18
Source File: CaffeineAsyncLoadingTest.java From promregator with Apache License 2.0 | 5 votes |
@Test public void testRefreshIsAsynchronous() throws InterruptedException { FakeTicker ticker = new FakeTicker(); AsyncLoadingCache<String, Integer> subject = Caffeine.newBuilder() .expireAfterAccess(240, TimeUnit.SECONDS) .refreshAfterWrite(120, TimeUnit.SECONDS) .ticker(ticker::read) .recordStats() .buildAsync(new AsyncCacheLoaderTimingImplementation()); log.info("Starting first request"); Assert.assertEquals(new Integer(0), Mono.fromFuture(subject.get("a")).block()); log.info("Stats on cache: "+subject.synchronous().stats().toString()); ticker.advance(Duration.ofSeconds(10)); log.info("Sending second request"); Assert.assertEquals(new Integer(0), Mono.fromFuture(subject.get("a")).block()); log.info("Stats on cache: "+subject.synchronous().stats().toString()); ticker.advance(Duration.ofSeconds(120)); log.info("Sending third request"); Assert.assertEquals(new Integer(0), Mono.fromFuture(subject.get("a")).block()); // That's the interesting case here! Note the zero above: This means that we get old cache data (which is what we want!) log.info("Stats on cache: "+subject.synchronous().stats().toString()); ticker.advance(Duration.ofSeconds(10)); Thread.sleep(250); // wait until async loading took place log.info("Sending fourth request"); Assert.assertEquals(new Integer(1), Mono.fromFuture(subject.get("a")).block()); log.info("Stats on cache: "+subject.synchronous().stats().toString()); }
Example #19
Source File: ParsecAsyncHttpResponseLoadingCache.java From parsec-libraries with Apache License 2.0 | 5 votes |
/** * Constructor. * @param client client */ public Builder(final ParsecAsyncHttpClient client) { caffeine = Caffeine.newBuilder(); this.client = client; cleanUpInterval = DEFAULT_CLEANUP_INTERVAL; cleanUpTimeUnit = TimeUnit.SECONDS; }
Example #20
Source File: WindowLookback.java From metron with Apache License 2.0 | 5 votes |
@Override public void initialize(Context context) { windowCache = Caffeine.newBuilder() .maximumSize(200) .expireAfterAccess(10, TimeUnit.MINUTES) .build(); }
Example #21
Source File: NoBootTest.java From zuihou-admin-cloud with Apache License 2.0 | 5 votes |
@Test public void test() { Cache<String, Object> cache = Caffeine.newBuilder() .maximumSize(100) .build(); Object val = cache.get("zuihouaa", (key) -> "延迟加载" + key); System.out.println(val); System.out.println(cache.getIfPresent("zuihouaa")); }
Example #22
Source File: ImportantStatementComparator.java From inception with Apache License 2.0 | 5 votes |
public ImportantStatementComparator(Function<StatementGroupBean, T> aKeyExtractor, Function<T, Boolean> aImportant) { keyExtractor = aKeyExtractor; important = aImportant; cache = Caffeine.newBuilder().build(key -> important.apply(key) ? 0 : 1); }
Example #23
Source File: EmptyCachesTest.java From caffeine with Apache License 2.0 | 5 votes |
public void testEqualsAndHashCode_different() { for (Caffeine<Object, Object> builder : cacheFactory().buildAllPermutations()) { // all caches should be different: instance equality new EqualsTester() .addEqualityGroup(CaffeinatedGuava.build(builder, identityLoader())) .addEqualityGroup(CaffeinatedGuava.build(builder, identityLoader())) .addEqualityGroup(CaffeinatedGuava.build(builder, identityLoader())) .testEquals(); } }
Example #24
Source File: CacheExpirationTest.java From caffeine with Apache License 2.0 | 5 votes |
public void testRemovalScheduler_expireAfterBoth() { FakeTicker ticker = new FakeTicker(); CountingRemovalListener<String, Integer> removalListener = countingRemovalListener(); WatchedCreatorLoader loader = new WatchedCreatorLoader(); LoadingCache<String, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder() .expireAfterAccess(EXPIRING_TIME, MILLISECONDS) .expireAfterWrite(EXPIRING_TIME, MILLISECONDS) .executor(MoreExecutors.directExecutor()) .removalListener(removalListener) .ticker(ticker::read), loader); runRemovalScheduler(cache, removalListener, loader, ticker, KEY_PREFIX, EXPIRING_TIME); }
Example #25
Source File: CacheExpirationTest.java From caffeine with Apache License 2.0 | 5 votes |
public void testExpiration_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); checkExpiration(cache, loader, ticker, removalListener); }
Example #26
Source File: SnipeCommand.java From kyoko with MIT License | 5 votes |
@Override public void onRegister() { messageCache = Caffeine.newBuilder().maximumSize(150).softValues().build(); snipes = new WeakHashMap<>(); consumers.add(eventManager.registerEventHandler(DiscordEvent.MESSAGE_CREATE, this::onMessage)); consumers.add(eventManager.registerEventHandler(DiscordEvent.MESSAGE_DELETE, this::onDelete)); consumers.add(eventManager.registerEventHandler(DiscordEvent.MESSAGE_UPDATE, this::onEdit)); }
Example #27
Source File: RateLimitService.java From zhcet-web with Apache License 2.0 | 5 votes |
public RateLimitService() { attemptsCache = Caffeine .newBuilder() .maximumSize(1000) .expireAfterWrite(Duration.of(EXPIRE_TIME, TIME_UNIT)) .build(); }
Example #28
Source File: CacheAutoConfiguration.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
/** * @return the direct cache manager to access without tenant aware * check, cause in sometimes it's necessary to access the cache * directly without having the current tenant, e.g. initial * creation of tenant */ @Bean(name = "directCacheManager") @ConditionalOnMissingBean(name = "directCacheManager") public CacheManager directCacheManager(final CacheProperties cacheProperties) { final CaffeineCacheManager cacheManager = new CaffeineCacheManager(); if (cacheProperties.getTtl() > 0) { final Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder() .expireAfterWrite(cacheProperties.getTtl(), cacheProperties.getTtlUnit()); cacheManager.setCaffeine(cacheBuilder); } return cacheManager; }
Example #29
Source File: CaffeineCacheFactory.java From cache2k-benchmark with Apache License 2.0 | 5 votes |
private Caffeine createCache(final int _maxElements) { Caffeine b = Caffeine.newBuilder().maximumSize(_maxElements); if (sameThreadEviction) { b.executor(Runnable::run); } if (fullEvictionCapacity) { b.initialCapacity(_maxElements); } if (withExpiry) { b.expireAfterWrite(2 * 60, TimeUnit.SECONDS); } return b; }
Example #30
Source File: CaffeineAsyncLoadingTest.java From promregator with Apache License 2.0 | 5 votes |
@Test public void testFailureOnAsynchronous() { FakeTicker ticker = new FakeTicker(); AsyncLoadingCache<String, Integer> subject = Caffeine.newBuilder() .expireAfterAccess(240, TimeUnit.SECONDS) .refreshAfterWrite(120, TimeUnit.SECONDS) .ticker(ticker::read) .recordStats() .buildAsync(new AsyncCacheLoaderFailureImplementation()); Assert.assertEquals(new Integer(0), Mono.fromFuture(subject.get("a")).block()); ticker.advance(Duration.ofSeconds(10)); Assert.assertEquals(new Integer(0), Mono.fromFuture(subject.get("a")).block()); ticker.advance(Duration.ofSeconds(250)); Mono<Integer> errorMono = Mono.fromFuture(subject.get("a")); boolean thrown = false; try { errorMono.block(); thrown = false; } catch (Throwable t) { thrown = true; } Assert.assertTrue(thrown); }