@Override public <K, V, C extends Configuration<K, V>> Cache<K, V> newCache( final String cacheName, final C configuration) { CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); if (configuration instanceof CompleteConfiguration) { configureCacheBuilder((CompleteConfiguration) configuration, cacheBuilder); } return new WrappedCache<K, V>(cacheBuilder.<K, V>build()) { @Override public String getName() { return cacheName; } @Override public CacheManager getCacheManager() { return GuavaCacheManager.this; } @Override public void close() { if (!isClosed()) { super.close(); destroyCache(cacheName); } } @Override public <T extends Configuration<K, V>> T getConfiguration(Class<T> clazz) { return Constants.unwrap(configuration, clazz); } }; }
static { // TODO where to obtain this from? CONFIGURATION = new HashConfiguration(); LOOKUPS = WealdMetrics.getMetricRegistry() .meter(com.codahale.metrics.MetricRegistry.name(Hash.class, "lookups")); MISSES = WealdMetrics.getMetricRegistry() .meter(com.codahale.metrics.MetricRegistry.name(Hash.class, "misses")); GETS = WealdMetrics.getMetricRegistry() .timer(com.codahale.metrics.MetricRegistry.name(Hash.class, "gets")); final CacheBuilder<Object, Object> cb = CacheBuilder.newBuilder() .maximumSize(CONFIGURATION.getCacheConfiguration().getMaxEntries()) .expireAfterWrite( CONFIGURATION.getCacheConfiguration().getMaxDuration(), TimeUnit.SECONDS); CACHE = cb.recordStats() .build( new CacheLoader<TwoTuple<String, String>, Boolean>() { @Override public Boolean load(final TwoTuple<String, String> input) { MISSES.mark(); return calculateMatches(input.getS(), input.getT()); } }); }
private void initCaches(FilterConfig filterConfig) { ArtifactorySystemProperties properties = ((ArtifactoryHome) filterConfig.getServletContext().getAttribute(ArtifactoryHome.SERVLET_CTX_ATTR)) .getArtifactoryProperties(); ConstantValues idleTimeSecsProp = ConstantValues.securityAuthenticationCacheIdleTimeSecs; long cacheIdleSecs = properties.getLongProperty(idleTimeSecsProp); ConstantValues initSizeProp = ConstantValues.securityAuthenticationCacheInitSize; long initSize = properties.getLongProperty(initSizeProp); nonUiAuthCache = CacheBuilder.newBuilder() .softValues() .initialCapacity((int) initSize) .expireAfterWrite(cacheIdleSecs, TimeUnit.SECONDS) .<AuthCacheKey, Authentication>build() .asMap(); userChangedCache = CacheBuilder.newBuilder() .softValues() .initialCapacity((int) initSize) .expireAfterWrite(cacheIdleSecs, TimeUnit.SECONDS) .<String, AuthenticationCache>build() .asMap(); SecurityService securityService = context.beanForType(SecurityService.class); securityService.addListener(this); }
public void testTimeToIdle_negative() { CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>(); try { builder.expireAfterAccess(-1, SECONDS); fail(); } catch (IllegalArgumentException expected) { } }
public void testInitialCapacity_negative() { CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>(); try { builder.initialCapacity(-1); fail(); } catch (IllegalArgumentException expected) { } }
public void testConcurrencyLevel_zero() { CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>(); try { builder.concurrencyLevel(0); fail(); } catch (IllegalArgumentException expected) { } }
public void testMaximumSize_negative() { CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>(); try { builder.maximumSize(-1); fail(); } catch (IllegalArgumentException expected) { } }
private static Cache<String, CacheObject> buildCache( /*int reloadAfterAccess, */ int reloadAfterWrite) { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder().softValues(); // if(reloadAfterAccess > 0) // builder.expireAfterAccess(reloadAfterAccess, TimeUnit.SECONDS); if (reloadAfterWrite > 0) builder.expireAfterWrite(reloadAfterWrite, TimeUnit.SECONDS); return builder.build(); }
public HashMapCacheRepository(long validFor) { if (validFor > 0) setExpiry(validFor); CacheBuilder builder = CacheBuilder.newBuilder(); if (validFor > 0) builder.expireAfterAccess(validFor, TimeUnit.MINUTES); cache = builder.build(); }
@GwtIncompatible("refreshAfterWrite") public void testRefresh_zero() { CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>(); try { builder.refreshAfterWrite(0, SECONDS); fail(); } catch (IllegalArgumentException expected) { } }
@GwtIncompatible("weakKeys") public void testKeyStrengthSetTwice() { CacheBuilder<Object, Object> builder1 = new CacheBuilder<Object, Object>().weakKeys(); try { builder1.weakKeys(); fail(); } catch (IllegalStateException expected) { } }
@GwtIncompatible("maximumWeight") public void testMaximumWeight_withoutWeigher() { CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>().maximumWeight(1); try { builder.build(identityLoader()); fail(); } catch (IllegalStateException expected) { } }
@GwtIncompatible("maximumWeight") public void testMaximumWeight_negative() { CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>(); try { builder.maximumWeight(-1); fail(); } catch (IllegalArgumentException expected) { } }
@GwtIncompatible("maximumWeight") public void testMaximumSize_andWeight() { CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>().maximumSize(16); try { builder.maximumWeight(16); fail(); } catch (IllegalStateException expected) { } }
public void testMaximumSize_setTwice() { CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>().maximumSize(16); try { // even to the same value is not allowed builder.maximumSize(16); fail(); } catch (IllegalStateException expected) { } }
public void testInitialCapacity_setTwice() { CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>().initialCapacity(16); try { // even to the same value is not allowed builder.initialCapacity(16); fail(); } catch (IllegalStateException expected) { } }
public void testConcurrencyLevel_setTwice() { CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>().concurrencyLevel(16); try { // even to the same value is not allowed builder.concurrencyLevel(16); fail(); } catch (IllegalStateException expected) { } }
public StandardTitanTx( StandardTitanGraph graph, TransactionConfig config, BackendTransaction txHandle) { Preconditions.checkNotNull(graph); Preconditions.checkArgument(graph.isOpen()); Preconditions.checkNotNull(config); Preconditions.checkNotNull(txHandle); this.graph = graph; this.config = config; this.idInspector = graph.getIDInspector(); this.txHandle = txHandle; temporaryID = new AtomicLong(-1); Cache<StandardElementQuery, List<Object>> indexCacheBuilder = CacheBuilder.newBuilder() .weigher( new Weigher<StandardElementQuery, List<Object>>() { @Override public int weigh(StandardElementQuery q, List<Object> r) { return 2 + r.size(); } }) .maximumWeight(DEFAULT_CACHE_SIZE) .build(); int concurrencyLevel; if (config.isSingleThreaded()) { vertexCache = new SimpleVertexCache(); addedRelations = new SimpleBufferAddedRelations(); concurrencyLevel = 1; typeCache = new HashMap<String, TitanType>(); newVertexIndexEntries = new SimpleIndexCache(); } else { vertexCache = new ConcurrentVertexCache(); addedRelations = new ConcurrentBufferAddedRelations(); concurrencyLevel = 4; typeCache = new ConcurrentHashMap<String, TitanType>(); newVertexIndexEntries = new ConcurrentIndexCache(); } for (SystemType st : SystemKey.values()) typeCache.put(st.getName(), st); indexCache = CacheBuilder.newBuilder() .weigher( new Weigher<StandardElementQuery, List<Object>>() { @Override public int weigh(StandardElementQuery q, List<Object> r) { return 2 + r.size(); } }) .concurrencyLevel(concurrencyLevel) .maximumWeight(DEFAULT_CACHE_SIZE) .build(); uniqueLocks = UNINITIALIZED_LOCKS; deletedRelations = EMPTY_DELETED_RELATIONS; this.isOpen = true; }
public void testTicker_setTwice() { Ticker testTicker = Ticker.systemTicker(); CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>().ticker(testTicker); try { // even to the same instance is not allowed builder.ticker(testTicker); fail(); } catch (IllegalStateException expected) { } }
public void testTimeToIdle_setTwice() { CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>().expireAfterAccess(3600, SECONDS); try { // even to the same value is not allowed builder.expireAfterAccess(3600, SECONDS); fail(); } catch (IllegalStateException expected) { } }
@PostConstruct private void init() { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); Cache<Serializable, WebSession> graphs = builder .expireAfterAccess(expireTime, TimeUnit.SECONDS) .initialCapacity(1000) .removalListener(listener) .build(); memoryRepository = new ExpiredCache<Serializable, WebSession>(graphs); }
@GwtIncompatible("refreshAfterWrite") public void testRefresh_setTwice() { CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>().refreshAfterWrite(3600, SECONDS); try { // even to the same value is not allowed builder.refreshAfterWrite(3600, SECONDS); fail(); } catch (IllegalStateException expected) { } }
public void testRemovalListener_setTwice() { RemovalListener<Object, Object> testListener = nullRemovalListener(); CacheBuilder<Object, Object> builder = new CacheBuilder<Object, Object>().removalListener(testListener); try { // even to the same instance is not allowed builder = builder.removalListener(testListener); fail(); } catch (IllegalStateException expected) { } }
/** * Specifies a listener instance that caches should notify each time an entry is removed for any * {@linkplain RemovalCause reason}. Each cache created by this builder will invoke this listener * as part of the routine maintenance described in the class documentation above. * * <p><b>Warning:</b> after invoking this method, do not continue to use <i>this</i> cache builder * reference; instead use the reference this method <i>returns</i>. At runtime, these point to the * same instance, but only the returned reference has the correct generic type information so as * to ensure type safety. For best results, use the standard method-chaining idiom illustrated in * the class documentation above, configuring a builder and building your cache in a single * statement. Failure to heed this advice can result in a {@link ClassCastException} being thrown * by a cache operation at some <i>undefined</i> point in the future. * * <p><b>Warning:</b> any exception thrown by {@code listener} will <i>not</i> be propagated to * the {@code Cache} user, only logged via a {@link Logger}. * * @return the cache builder reference that should be used instead of {@code this} for any * remaining configuration and cache building * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalStateException if a removal listener was already set */ @CheckReturnValue public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener( RemovalListener<? super K1, ? super V1> listener) { checkState(this.removalListener == null); // safely limiting the kinds of caches this can produce @SuppressWarnings("unchecked") CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this; me.removalListener = checkNotNull(listener); return me; }
public JWKSetCacheService() { this.validators = CacheBuilder.newBuilder() .expireAfterWrite(1, TimeUnit.HOURS) // expires 1 hour after fetch .maximumSize(100) .build(new JWKSetVerifierFetcher()); this.encrypters = CacheBuilder.newBuilder() .expireAfterWrite(1, TimeUnit.HOURS) // expires 1 hour after fetch .maximumSize(100) .build(new JWKSetEncryptorFetcher()); }
@SuppressWarnings({"rawtypes", "unchecked"}) @PostConstruct private void init() { String cacheName = getActiveSessionsCacheName(); CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); com.google.common.cache.Cache graphs = builder .expireAfterAccess(30, TimeUnit.MINUTES) .initialCapacity(10000) .removalListener(listener) .build(); org.springframework.cache.Cache guavaCache = new GuavaCache(cacheName, graphs); Cache cache = new DelegateCache(guavaCache); setActiveSessionsCache(cache); }
/** * Default constructor. Specify the size of the blocks, number of blocks, and the SlabCache this * cache will be assigned to. * * @param blockSize the size of each block, in bytes * @param numBlocks the number of blocks of blockSize this cache will hold. * @param master the SlabCache this SingleSlabCache is assigned to. */ public SingleSizeCache(int blockSize, int numBlocks, SlabItemActionWatcher master) { this.blockSize = blockSize; this.numBlocks = numBlocks; backingStore = new Slab(blockSize, numBlocks); this.stats = new CacheStats(); this.actionWatcher = master; this.size = new AtomicLong(CACHE_FIXED_OVERHEAD + backingStore.heapSize()); this.timeSinceLastAccess = new AtomicLong(); // This evictionListener is called whenever the cache automatically // evicts something. RemovalListener<BlockCacheKey, CacheablePair> listener = new RemovalListener<BlockCacheKey, CacheablePair>() { @Override public void onRemoval(RemovalNotification<BlockCacheKey, CacheablePair> notification) { if (!notification.wasEvicted()) { // Only process removals by eviction, not by replacement or // explicit removal return; } CacheablePair value = notification.getValue(); timeSinceLastAccess.set(System.nanoTime() - value.recentlyAccessed.get()); stats.evict(); doEviction(notification.getKey(), value); } }; backingMap = CacheBuilder.newBuilder() .maximumSize(numBlocks - 1) .removalListener(listener) .<BlockCacheKey, CacheablePair>build() .asMap(); }
TopLevelItemsCache() { cache = CacheBuilder.newBuilder() .initialCapacity(INITIAL_CAPACITY) .expireAfterAccess(EVICT_IN_SECONDS, TimeUnit.SECONDS) .maximumSize(MAX_ENTRIES) .softValues() .removalListener( new RemovalListener<LazyTopLevelItem.Key, TopLevelItem>() { @Override public void onRemoval( RemovalNotification<LazyTopLevelItem.Key, TopLevelItem> notification) { // System.out.println("*** Removed from cache " + notification.getKey().name ); } }) .build( new CacheLoader<LazyTopLevelItem.Key, TopLevelItem>() { Map<String, Integer> map = new HashMap<String, Integer>(); @Override public TopLevelItem load(LazyTopLevelItem.Key key) throws Exception { TopLevelItem item = (TopLevelItem) key.configFile.read(); item.onLoad(key.parent, key.name); return item; } }); }
/** * Constructor for CacheDataSource. * * @param src DataSource */ public CacheDataSource(DataSource src) { source = src; executorService = MoreExecutors.listeningDecorator( Executors.newCachedThreadPool( new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("AuthMe-CacheLoader") .build())); cachedAuths = CacheBuilder.newBuilder() .refreshAfterWrite(5, TimeUnit.MINUTES) .expireAfterAccess(15, TimeUnit.MINUTES) .build( new CacheLoader<String, Optional<PlayerAuth>>() { @Override public Optional<PlayerAuth> load(String key) { return Optional.fromNullable(source.getAuth(key)); } @Override public ListenableFuture<Optional<PlayerAuth>> reload( final String key, Optional<PlayerAuth> oldValue) { return executorService.submit( new Callable<Optional<PlayerAuth>>() { @Override public Optional<PlayerAuth> call() { ConsoleLogger.debug("REFRESH " + key); return load(key); } }); } }); }
private LoadingCache<DatasourceMonth, DataFileWriter<GenericRecord>> createWritersCache() { CacheLoader<DatasourceMonth, DataFileWriter<GenericRecord>> loader = new CacheLoader<DatasourceMonth, DataFileWriter<GenericRecord>>() { @Override public DataFileWriter<GenericRecord> load(DatasourceMonth datasourceMonth) throws Exception { return AvroWriterBolt.this.openHDFSFile(datasourceMonth); } }; // A synchronous removal listener should be enough in principle RemovalListener<DatasourceMonth, DataFileWriter<GenericRecord>> removalListener = new RemovalListener<DatasourceMonth, DataFileWriter<GenericRecord>>() { @Override public void onRemoval( RemovalNotification<DatasourceMonth, DataFileWriter<GenericRecord>> removal) { try { LOGGER.info("Closing file for datasource {}", removal.getKey().datasource()); removal.getValue().close(); } catch (IOException ioe) { LOGGER.error( "Error closing file for datasource {}: {}", removal.getKey().datasource(), ioe.getMessage()); throw new RuntimeException(ioe); } } }; return CacheBuilder.newBuilder() .expireAfterAccess(CACHE_EXPIRATION_TIME, TimeUnit.MINUTES) .removalListener(removalListener) .build(loader); }