public NetworkLocationCache(NetworkTopology networkTopology) { this.networkTopology = requireNonNull(networkTopology, "networkTopology is null"); this.cache = CacheBuilder.newBuilder() .expireAfterWrite(1, DAYS) .refreshAfterWrite(12, HOURS) .build(asyncReloading(CacheLoader.from(this::locate), executor)); this.negativeCache = CacheBuilder.newBuilder() .expireAfterWrite(NEGATIVE_CACHE_DURATION.toMillis(), MILLISECONDS) .build(); }
@Inject public ExpressionCompiler(Metadata metadata, PageFunctionCompiler pageFunctionCompiler) { requireNonNull(metadata, "metadata is null"); this.pageFunctionCompiler = requireNonNull(pageFunctionCompiler, "pageFunctionCompiler is null"); this.cursorProcessors = CacheBuilder.newBuilder() .recordStats() .maximumSize(1000) .build(CacheLoader.from(key -> compile(key.getFilter(), key.getProjections(), new CursorProcessorCompiler(metadata), CursorProcessor.class))); this.cacheStatsMBean = new CacheStatsMBean(cursorProcessors); }
public void testRemovalScheduler_expireAfterBoth() { FakeTicker ticker = new FakeTicker(); CountingRemovalListener<String, Integer> removalListener = countingRemovalListener(); WatchedCreatorLoader loader = new WatchedCreatorLoader(); LoadingCache<String, Integer> cache = CacheBuilder.newBuilder() .expireAfterAccess(EXPIRING_TIME, MILLISECONDS) .expireAfterWrite(EXPIRING_TIME, MILLISECONDS) .removalListener(removalListener) .ticker(ticker) .build(loader); runRemovalScheduler(cache, removalListener, loader, ticker, KEY_PREFIX, EXPIRING_TIME); }
@Override public void setUp() throws Exception { super.setUp(); this.cache = CacheBuilder.newBuilder() .expireAfterAccess(500000, TimeUnit.MILLISECONDS) .maximumSize(count) .build(); }
public void testBulkLoad_partial() throws ExecutionException { final Object extraKey = new Object(); final Object extraValue = new Object(); CacheLoader<Object, Object> loader = new CacheLoader<Object, Object>() { @Override public Object load(Object key) throws Exception { throw new AssertionError(); } @Override public Map<Object, Object> loadAll(Iterable<?> keys) throws Exception { Map<Object, Object> result = Maps.newHashMap(); // ignore request keys result.put(extraKey, extraValue); return result; } }; LoadingCache<Object, Object> cache = CacheBuilder.newBuilder().build(loader); Object[] lookupKeys = new Object[] {new Object(), new Object(), new Object()}; try { cache.getAll(asList(lookupKeys)); fail(); } catch (InvalidCacheLoadException expected) { } assertSame(extraValue, cache.asMap().get(extraKey)); }
@Provides @Singleton public LoadingCache<Credentials, AuthenticationResponse> provideAuthenticationResponseCache( GetAuthenticationResponse getAuthenticationResponse) { return CacheBuilder.newBuilder().expireAfterWrite(23, TimeUnit.HOURS).build(getAuthenticationResponse); }
@Provides @Singleton protected LoadingCache<String, Node> provideNodeStore(Map<String, YamlNode> backing, Function<Node, YamlNode> yamlSerializer, Function<YamlNode, Node> yamlDeserializer) { return CacheBuilder.newBuilder().build(CacheLoader.from(Functions.forMap(new TransformingMap<String, YamlNode, Node>(backing, yamlDeserializer, yamlSerializer)))); }
GcMonitor gcMonitor) requireNonNull(nodeInfo, "nodeInfo is null"); requireNonNull(config, "config is null"); infoCacheTime = config.getInfoMaxAge(); clientTimeout = config.getClientTimeout(); taskNotificationExecutorMBean = new ThreadPoolExecutorMBean((ThreadPoolExecutor) taskNotificationExecutor); this.taskManagementExecutor = requireNonNull(taskManagementExecutor, "taskManagementExecutor cannot be null").getExecutor(); this.driverYieldExecutor = newScheduledThreadPool(config.getTaskYieldThreads(), threadsNamed("task-yield-%s")); DataSize maxQuerySpillPerNode = nodeSpillConfig.getQueryMaxSpillPerNode(); queryContexts = CacheBuilder.newBuilder().weakValues().build(CacheLoader.from( queryId -> createQueryContext(queryId, localMemoryManager, nodeMemoryConfig, localSpillManager, gcMonitor, maxQueryUserMemoryPerNode, maxQueryTotalMemoryPerNode, maxQuerySpillPerNode))); tasks = CacheBuilder.newBuilder().build(CacheLoader.from( taskId -> createSqlTask( taskId, locationFactory.createLocalTaskLocation(taskId), nodeInfo.getNodeId(), queryContexts.getUnchecked(taskId.getQueryId()), sqlTaskExecutionFactory, taskNotificationExecutor,
public void testReloadAfterValueReclamation() throws InterruptedException, ExecutionException { CountingLoader countingLoader = new CountingLoader(); LoadingCache<Object, Object> cache = CacheBuilder.newBuilder().weakValues().build(countingLoader); ConcurrentMap<Object, Object> map = cache.asMap(); expectedComputations++; ref = new WeakReference<>(cache.getUnchecked(1)); oldValue = null; Thread.sleep(i); expectedComputations++; cache.refresh(1); checkNothingLogged(); ref = new WeakReference<>(map.get(1)); oldValue = null; Thread.sleep(i);
public void testBulkLoadNull() throws ExecutionException { LoadingCache<Object, Object> cache = CacheBuilder.newBuilder().recordStats().build(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()); }
@Provides public CachedUserStorage getCachedEventStorage( JournalUserStorage journalUserStorage, @Named("eventhub.cacheduserstorage.recordCacheSize") int recordCacheSize) { Cache<Integer, User> userCache = CacheBuilder.newBuilder() .maximumSize(recordCacheSize) .recordStats() .build(); return new CachedUserStorage(journalUserStorage, userCache); }
LoadingCache<Object, Object> cache = CacheBuilder.newBuilder().recordStats().build(loader); Object key = new Object(); CacheStats stats = cache.stats(); assertEquals(0, stats.missCount()); assertEquals(0, stats.loadSuccessCount()); assertEquals(0, stats.loadExceptionCount()); assertEquals(0, stats.hitCount()); assertSame(one, cache.getUnchecked(key)); stats = cache.stats(); assertEquals(1, stats.missCount()); assertEquals(1, stats.loadSuccessCount());
public void testEviction_invalidateAll() { // test that .invalidateAll() resets total weight state correctly IdentityLoader<Integer> loader = identityLoader(); LoadingCache<Integer, Integer> cache = CacheBuilder.newBuilder().concurrencyLevel(1).maximumSize(10).build(loader); Set<Integer> keySet = cache.asMap().keySet(); assertThat(keySet).isEmpty(); // add 0, 1, 2, 3, 4 getAll(cache, asList(0, 1, 2, 3, 4)); CacheTesting.drainRecencyQueues(cache); assertThat(keySet).containsExactly(0, 1, 2, 3, 4); // invalidate all cache.invalidateAll(); CacheTesting.drainRecencyQueues(cache); assertThat(keySet).isEmpty(); // add 5, 6, 7, 8, 9, 10, 11, 12 getAll(cache, asList(5, 6, 7, 8, 9, 10, 11, 12)); CacheTesting.drainRecencyQueues(cache); assertThat(keySet).containsExactly(5, 6, 7, 8, 9, 10, 11, 12); }
public CacheNodeStoreModule(Map<String, Node> backing) { this(CacheBuilder.newBuilder().<String, Node>build(CacheLoader.from(Functions.forMap(backing)))); for (String node : backing.keySet()) this.backing.getUnchecked(node); }
public void testEviction_overweight() { // test weighted lru within a single segment IdentityLoader<Integer> loader = identityLoader(); LoadingCache<Integer, Integer> cache = CacheBuilder.newBuilder() .concurrencyLevel(1) .maximumWeight(45) .weigher(intKeyWeigher()) .build(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); }
public void testGet_computeNull() { LoadingCache<Object, Object> cache = CacheBuilder.newBuilder() .maximumSize(0) .removalListener(listener) .build(constantLoader(null)); try { cache.getUnchecked(new Object()); fail(); } catch (InvalidCacheLoadException e) { /* expected */ } assertTrue(listener.isEmpty()); checkEmpty(cache); }
@GwtIncompatible // digs into internals of the non-GWT implementation public void testMaximumSize_largerThanInt() { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder().initialCapacity(512).maximumSize(Long.MAX_VALUE); LocalCache<?, ?> cache = ((LocalCache.LocalManualCache<?, ?>) builder.build()).localCache; assertThat(cache.segments.length * cache.segments[0].table.length()).isEqualTo(512); }
@GwtIncompatible // CacheTesting public void testNullCache() { CountingRemovalListener<Object, Object> listener = countingRemovalListener(); LoadingCache<Object, Object> nullCache = CacheBuilder.newBuilder().maximumSize(0).removalListener(listener).build(identityLoader()); assertEquals(0, nullCache.size()); Object key = new Object(); assertSame(key, nullCache.getUnchecked(key)); assertEquals(1, listener.getCount()); assertEquals(0, nullCache.size()); CacheTesting.checkEmpty(nullCache.asMap()); }
public void testComputeEviction() { // b/80241237 Cache<String, String> c = CacheBuilder.newBuilder().maximumSize(1).build(); 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(""); }
public void testEviction_maxSizeOneSegment() { IdentityLoader<Integer> loader = identityLoader(); LoadingCache<Integer, Integer> cache = CacheBuilder.newBuilder().concurrencyLevel(1).maximumSize(MAX_SIZE).build(loader); for (int i = 0; i < 2 * MAX_SIZE; i++) { cache.getUnchecked(i); assertEquals(Math.min(i + 1, MAX_SIZE), cache.size()); } assertEquals(MAX_SIZE, cache.size()); CacheTesting.checkValidState(cache); }