List of usage examples for com.google.common.cache CacheBuilder expireAfterWrite
public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit)
From source file:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestResourceServiceImpl.java
protected LoadingCache<String, Sardine> buildSardineCache() { CacheProperties cacheProperties = properties.getResourceService().getSardineCache(); CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); if (cacheProperties.getConcurrencyLevel() != null) { builder.concurrencyLevel(cacheProperties.getConcurrencyLevel()); }/*ww w .j a v a2 s. c o m*/ if (cacheProperties.getExpireAfterAccess() != null && cacheProperties.getExpireAfterAccessTimeUnit() != null) { builder.expireAfterAccess(cacheProperties.getExpireAfterAccess(), cacheProperties.getExpireAfterAccessTimeUnit()); } if (cacheProperties.getExpireAfterWrite() != null && cacheProperties.getExpireAfterWriteTimeUnit() != null) { builder.expireAfterWrite(cacheProperties.getExpireAfterWrite(), cacheProperties.getExpireAfterWriteTimeUnit()); } if (cacheProperties.getInitialCapacity() != null) { builder.initialCapacity(cacheProperties.getInitialCapacity()); } if (cacheProperties.getMaximumSize() != null) { builder.maximumSize(cacheProperties.getMaximumSize()); } if (cacheProperties.getMaximumWeight() != null) { builder.maximumWeight(cacheProperties.getMaximumWeight()); } if (cacheProperties.getRefreshAfterWrite() != null && cacheProperties.getRefreshAfterWriteTimeUnit() != null) { builder.refreshAfterWrite(cacheProperties.getRefreshAfterWrite(), cacheProperties.getRefreshAfterWriteTimeUnit()); } return builder.build(sardineCacheLoader); }
From source file:com.github.benmanes.multiway.TransferPool.java
/** Creates the denormalized cache of resources based on the builder configuration. */ Cache<ResourceKey<K>, R> __makeCache(MultiwayPoolBuilder<? super K, ? super R> builder) { CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); if (builder.maximumSize != MultiwayPoolBuilder.UNSET_INT) { cacheBuilder.maximumSize(builder.maximumSize); }/*from www . j a v a2s .co m*/ if (builder.maximumWeight != MultiwayPoolBuilder.UNSET_INT) { cacheBuilder.maximumWeight(builder.maximumWeight); } if (builder.weigher != null) { final Weigher<? super K, ? super R> weigher = builder.weigher; cacheBuilder.weigher(new Weigher<ResourceKey<K>, R>() { @Override public int weigh(ResourceKey<K> resourceKey, R resource) { return weigher.weigh(resourceKey.getKey(), resource); } }); } if (builder.expireAfterWriteNanos != MultiwayPoolBuilder.UNSET_INT) { cacheBuilder.expireAfterWrite(builder.expireAfterWriteNanos, TimeUnit.NANOSECONDS); } if (builder.ticker != null) { cacheBuilder.ticker(builder.ticker); } if (builder.recordStats) { cacheBuilder.recordStats(); } cacheBuilder.concurrencyLevel(builder.getConcurrencyLevel()); cacheBuilder.removalListener(new CacheRemovalListener()); return cacheBuilder.build(); }
From source file:org.artifactory.repo.RemoteRepoBase.java
private <V> Map<String, V> initCache(int initialCapacity, long expirationSeconds, boolean softValues) { CacheBuilder cacheBuilder = CacheBuilder.newBuilder().initialCapacity(initialCapacity); if (expirationSeconds >= 0) { cacheBuilder.expireAfterWrite(expirationSeconds, TimeUnit.SECONDS); }// w w w.j a va 2 s. c om if (softValues) { cacheBuilder.softValues(); } //noinspection unchecked return cacheBuilder.build().asMap(); }
From source file:org.artifactory.bintray.BintrayServiceImpl.java
private <V> Map<String, V> initCache(int initialCapacity, long expirationSeconds, boolean softValues) { CacheBuilder mapMaker = CacheBuilder.newBuilder().initialCapacity(initialCapacity); if (expirationSeconds >= 0) { mapMaker.expireAfterWrite(expirationSeconds, TimeUnit.SECONDS); }/*w w w .j av a 2s. co m*/ if (softValues) { mapMaker.softValues(); } //noinspection unchecked return mapMaker.build().asMap(); }
From source file:org.apache.ambari.server.security.encryption.InMemoryCredentialStoreService.java
/** * Constructs a new InMemoryCredentialStoreService with a specified credential timeout * * @param retentionDuration the time in some units to keep stored credentials, from the time they are added * @param units the units for the retention duration (minutes, seconds, etc...) * @param activelyPurge true to actively purge credentials after the retention time has expired; * otherwise false, to passively purge credentials after the retention time has expired *///from ww w .j av a 2s.co m public InMemoryCredentialStoreService(final long retentionDuration, final TimeUnit units, boolean activelyPurge) { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); // If the retentionDuration is less the 1, then no retention policy is to be enforced if (retentionDuration > 0) { // If actively purging expired credentials, set up a timer to periodically clean the cache if (activelyPurge) { ThreadFactory threadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread t = Executors.defaultThreadFactory().newThread(runnable); if (t != null) { t.setName(String.format("%s active cleanup timer", InMemoryCredentialStoreService.class.getSimpleName())); t.setDaemon(true); } return t; } }; Runnable runnable = new Runnable() { @Override public void run() { if (LOG.isDebugEnabled()) { LOG.debug("Cleaning up cache due to retention timeout of {} milliseconds", units.toMillis(retentionDuration)); } cache.cleanUp(); } }; Executors.newSingleThreadScheduledExecutor(threadFactory).schedule(runnable, 1, TimeUnit.MINUTES); } builder.expireAfterWrite(retentionDuration, units); } cache = builder.build(); }
From source file:org.apache.ambari.server.security.encryption.InMemoryCredentialStore.java
/** * Constructs a new InMemoryCredentialStore with a specified credential timeout * * @param retentionDuration the time in some units to keep stored credentials, from the time they are added * @param units the units for the retention duration (minutes, seconds, etc...) * @param activelyPurge true to actively purge credentials after the retention time has expired; * otherwise false, to passively purge credentials after the retention time has expired */// w ww .ja v a 2 s. c o m public InMemoryCredentialStore(final long retentionDuration, final TimeUnit units, boolean activelyPurge) { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); // If the retentionDuration is less the 1, then no retention policy is to be enforced if (retentionDuration > 0) { // If actively purging expired credentials, set up a timer to periodically clean the cache if (activelyPurge) { ThreadFactory threadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread t = Executors.defaultThreadFactory().newThread(runnable); if (t != null) { t.setName(String.format("%s active cleanup timer", InMemoryCredentialStore.class.getSimpleName())); t.setDaemon(true); } return t; } }; Runnable runnable = new Runnable() { @Override public void run() { if (LOG.isDebugEnabled()) { LOG.debug("Cleaning up cache due to retention timeout of {} milliseconds", units.toMillis(retentionDuration)); } cache.cleanUp(); } }; Executors.newSingleThreadScheduledExecutor(threadFactory).schedule(runnable, 1, TimeUnit.MINUTES); } builder.expireAfterWrite(retentionDuration, units); } cache = builder.build(); }
From source file:org.geowebcache.storage.blobstore.memory.guava.GuavaCacheProvider.java
/** * This method is used for creating a new cache object, from the defined configuration. * //from ww w . j av a 2 s .c o m * @param configuration */ private void initCache(CacheConfiguration configuration) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Building new Cache"); } // Initialization step int concurrency = configuration.getConcurrencyLevel(); maxMemory = configuration.getHardMemoryLimit() * BYTES_TO_MB; long evictionTime = configuration.getEvictionTime(); EvictionPolicy policy = configuration.getPolicy(); // If Cache already exists, flush it if (cache != null) { cache.invalidateAll(); } // Create the CacheBuilder CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); // Add weigher Weigher<String, TileObject> weigher = new Weigher<String, TileObject>() { @Override public int weigh(String key, TileObject value) { currentSize.addAndGet(value.getBlobSize()); return value.getBlobSize(); } }; // Create the builder CacheBuilder<String, TileObject> newBuilder = builder.maximumWeight(maxMemory).recordStats() .weigher(weigher).concurrencyLevel(concurrency) .removalListener(new RemovalListener<String, TileObject>() { @Override public void onRemoval(RemovalNotification<String, TileObject> notification) { // TODO This operation is not atomic TileObject obj = notification.getValue(); // Update the current size currentSize.addAndGet(-obj.getBlobSize()); final String tileKey = generateTileKey(obj); final String layerName = obj.getLayerName(); multimap.removeTile(layerName, tileKey); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Removed tile " + tileKey + " for layer " + layerName + " due to reason:" + notification.getCause().toString()); LOGGER.debug("Removed tile was evicted? " + notification.wasEvicted()); } } }); // Handle eviction policy boolean configuredPolicy = false; if (policy != null && evictionTime > 0) { if (policy == EvictionPolicy.EXPIRE_AFTER_ACCESS) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Configuring Expire After Access eviction policy"); } newBuilder.expireAfterAccess(evictionTime, TimeUnit.SECONDS); configuredPolicy = true; } else if (policy == EvictionPolicy.EXPIRE_AFTER_WRITE) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Configuring Expire After Write eviction policy"); } newBuilder.expireAfterWrite(evictionTime, TimeUnit.SECONDS); configuredPolicy = true; } } // Build the cache cache = newBuilder.build(); // Created a new multimap multimap = new LayerMap(); // Configure a new scheduling task if needed if (configuredPolicy) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Configuring Scheduled Task for cache eviction"); } Runnable command = new Runnable() { @Override public void run() { if (configured.get()) { // Increment the number of current operations // This behavior is used in order to wait // the end of all the operations after setting // the configured parameter to false actualOperations.incrementAndGet(); try { cache.cleanUp(); } finally { // Decrement the number of current operations. actualOperations.decrementAndGet(); } } } }; // Initialization of the internal Scheduler task for scheduling cache cleanup scheduledPool = Executors.newScheduledThreadPool(CORE_POOL_SIZE); scheduledPool.scheduleAtFixedRate(command, 10, evictionTime + 1, TimeUnit.SECONDS); } // Update the configured parameter configured.getAndSet(true); }