List of usage examples for com.google.common.cache CacheBuilder expireAfterWrite
public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit)
From source file:com.github.benmanes.caffeine.cache.testing.GuavaLocalCache.java
/** Returns a Guava-backed cache. */ @SuppressWarnings("CheckReturnValue") public static <K, V> Cache<K, V> newGuavaCache(CacheContext context) { checkState(!context.isAsync(), "Guava caches are synchronous only"); CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); if (context.initialCapacity != InitialCapacity.DEFAULT) { builder.initialCapacity(context.initialCapacity.size()); }/*from w w w . ja v a2s .c o m*/ if (context.isRecordingStats()) { builder.recordStats(); } if (context.maximumSize != MaximumSize.DISABLED) { if (context.weigher == CacheWeigher.DEFAULT) { builder.maximumSize(context.maximumSize.max()); } else { builder.weigher(new GuavaWeigher<Object, Object>(context.weigher)); builder.maximumWeight(context.maximumWeight()); } } if (context.afterAccess != Expire.DISABLED) { builder.expireAfterAccess(context.afterAccess.timeNanos(), TimeUnit.NANOSECONDS); } if (context.afterWrite != Expire.DISABLED) { builder.expireAfterWrite(context.afterWrite.timeNanos(), TimeUnit.NANOSECONDS); } if (context.refresh != Expire.DISABLED) { builder.refreshAfterWrite(context.refresh.timeNanos(), TimeUnit.NANOSECONDS); } if (context.expires() || context.refreshes()) { builder.ticker(context.ticker()); } if (context.keyStrength == ReferenceType.WEAK) { builder.weakKeys(); } else if (context.keyStrength == ReferenceType.SOFT) { throw new IllegalStateException(); } if (context.valueStrength == ReferenceType.WEAK) { builder.weakValues(); } else if (context.valueStrength == ReferenceType.SOFT) { builder.softValues(); } if (context.removalListenerType != Listener.DEFAULT) { boolean translateZeroExpire = (context.afterAccess == Expire.IMMEDIATELY) || (context.afterWrite == Expire.IMMEDIATELY); builder.removalListener(new GuavaRemovalListener<>(translateZeroExpire, context.removalListener)); } Ticker ticker = (context.ticker == null) ? Ticker.systemTicker() : context.ticker; if (context.loader == null) { context.cache = new GuavaCache<>(builder.<Integer, Integer>build(), ticker); } else if (context.loader().isBulk()) { context.cache = new GuavaLoadingCache<>( builder.build(new BulkLoader<Integer, Integer>(context.loader())), ticker); } else { context.cache = new GuavaLoadingCache<>( builder.build(new SingleLoader<Integer, Integer>(context.loader())), ticker); } @SuppressWarnings("unchecked") Cache<K, V> castedCache = (Cache<K, V>) context.cache; return castedCache; }
From source file:org.nuxeo.ecm.core.storage.dbs.DBSCachingRepository.java
protected <T> Cache<String, T> newCache(DBSRepositoryDescriptor descriptor) { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); builder = builder.expireAfterWrite(descriptor.cacheTTL.longValue(), TimeUnit.MINUTES); if (descriptor.cacheConcurrencyLevel != null) { builder = builder.concurrencyLevel(descriptor.cacheConcurrencyLevel.intValue()); }/*from w w w. j a v a2 s. c o m*/ if (descriptor.cacheMaxSize != null) { builder = builder.maximumSize(descriptor.cacheMaxSize.longValue()); } return builder.build(); }
From source file:org.socraticgrid.workbench.service.KnowledgeModuleServiceProcessor.java
private KnowledgeModuleServiceProcessor() { try {// w ww. jav a 2s . c o m String implName = ApplicationSettings.getInstance().getSetting("knowledge.module.service.impl"); this.knowledgeModuleService = (KnowledgeModuleService) Class.forName(implName).newInstance(); useReferenceDataCache = Boolean.parseBoolean(ApplicationSettings.getInstance() .getSetting("knowledge.module.service.cache.enabled", "false")); if (useReferenceDataCache) { String maxCacheSize = ApplicationSettings.getInstance() .getSetting("knowledge.module.service.cache.maxsize"); String cacheExpirationTime = ApplicationSettings.getInstance() .getSetting("knowledge.module.service.cache.expiration"); CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); if (maxCacheSize != null) { cacheBuilder.maximumSize(Long.parseLong(maxCacheSize)); } if (cacheExpirationTime != null) { cacheBuilder.expireAfterWrite(Long.parseLong(maxCacheSize), TimeUnit.MINUTES); } this.referenceDataCache = cacheBuilder.build(); } } catch (Exception ex) { throw new IllegalStateException(ex); } }
From source file:org.elasticsearch.indices.cache.filter.terms.IndicesTermsFilterCache.java
@Inject public IndicesTermsFilterCache(Settings settings, Client client) { super(settings); this.client = client; ByteSizeValue size = componentSettings.getAsBytesSize("size", new ByteSizeValue(10, ByteSizeUnit.MB)); TimeValue expireAfterWrite = componentSettings.getAsTime("expire_after_write", null); TimeValue expireAfterAccess = componentSettings.getAsTime("expire_after_access", null); CacheBuilder<BytesRef, TermsFilterValue> builder = CacheBuilder.newBuilder().maximumWeight(size.bytes()) .weigher(new TermsFilterValueWeigher()); if (expireAfterAccess != null) { builder.expireAfterAccess(expireAfterAccess.millis(), TimeUnit.MILLISECONDS); }// www .j av a 2s. co m if (expireAfterWrite != null) { builder.expireAfterWrite(expireAfterWrite.millis(), TimeUnit.MILLISECONDS); } this.cache = builder.build(); }
From source file:org.apache.druid.server.lookup.cache.loading.OnHeapLoadingCache.java
/** * @param concurrencyLevel default to {@code DEFAULT_CONCURRENCY_LEVEL} * @param initialCapacity default to {@code DEFAULT_INITIAL_CAPACITY} * @param maximumSize Max number of entries that the cache can hold, When set to zero, elements will be evicted immediately after being loaded into the * cache./*from w w w .ja v a 2 s . co m*/ * When set to null, cache maximum size is infinity * @param expireAfterAccess 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 * access. Access time is reset by all cache read and write operations. * No read-time-based eviction when set to null. * @param expireAfterWrite 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. * No write-time-based eviction when set to null. */ @JsonCreator public OnHeapLoadingCache(@JsonProperty("concurrencyLevel") int concurrencyLevel, @JsonProperty("initialCapacity") int initialCapacity, @JsonProperty("maximumSize") Long maximumSize, @JsonProperty("expireAfterAccess") Long expireAfterAccess, @JsonProperty("expireAfterWrite") Long expireAfterWrite) { this.concurrencyLevel = concurrencyLevel <= 0 ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel; this.initialCapacity = initialCapacity <= 0 ? DEFAULT_INITIAL_CAPACITY : initialCapacity; this.maximumSize = maximumSize; this.expireAfterAccess = expireAfterAccess; this.expireAfterWrite = expireAfterWrite; CacheBuilder builder = CacheBuilder.newBuilder().concurrencyLevel(this.concurrencyLevel) .initialCapacity(this.initialCapacity).recordStats(); if (this.expireAfterAccess != null) { builder.expireAfterAccess(expireAfterAccess, TimeUnit.MILLISECONDS); } if (this.expireAfterWrite != null) { builder.expireAfterWrite(this.expireAfterWrite, TimeUnit.MILLISECONDS); } if (this.maximumSize != null) { builder.maximumSize(this.maximumSize); } this.cache = builder.build(); if (isClosed.getAndSet(false)) { log.info("Guava Based OnHeapCache started with spec [%s]", cache.toString()); } }
From source file:com.datatorrent.lib.db.cache.CacheStore.java
@Override public void connect() throws IOException { open = true;//from ww w . ja v a 2 s. c om CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); cacheBuilder.maximumSize(maxCacheSize); if (entryExpiryStrategy == ExpiryType.EXPIRE_AFTER_ACCESS) { cacheBuilder.expireAfterAccess(entryExpiryDurationInMillis, TimeUnit.MILLISECONDS); } else if (entryExpiryStrategy == ExpiryType.EXPIRE_AFTER_WRITE) { cacheBuilder.expireAfterWrite(entryExpiryDurationInMillis, TimeUnit.MILLISECONDS); } cache = cacheBuilder.build(); this.cleanupScheduler = Executors.newScheduledThreadPool(1); cleanupScheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { cache.cleanUp(); } }, cacheCleanupIntervalInMillis, cacheCleanupIntervalInMillis, TimeUnit.MILLISECONDS); }
From source file:com.github.benmanes.caffeine.cache.testing.GuavaCacheFromContext.java
/** Returns a Guava-backed cache. */ @SuppressWarnings("CheckReturnValue") public static <K, V> Cache<K, V> newGuavaCache(CacheContext context) { checkState(!context.isAsync(), "Guava caches are synchronous only"); CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); context.guava = builder;//from w ww. j av a2s. c o m builder.concurrencyLevel(1); if (context.initialCapacity != InitialCapacity.DEFAULT) { builder.initialCapacity(context.initialCapacity.size()); } if (context.isRecordingStats()) { builder.recordStats(); } if (context.maximumSize != Maximum.DISABLED) { if (context.weigher == CacheWeigher.DEFAULT) { builder.maximumSize(context.maximumSize.max()); } else { builder.weigher(new GuavaWeigher<Object, Object>(context.weigher)); builder.maximumWeight(context.maximumWeight()); } } if (context.afterAccess != Expire.DISABLED) { builder.expireAfterAccess(context.afterAccess.timeNanos(), TimeUnit.NANOSECONDS); } if (context.afterWrite != Expire.DISABLED) { builder.expireAfterWrite(context.afterWrite.timeNanos(), TimeUnit.NANOSECONDS); } if (context.refresh != Expire.DISABLED) { builder.refreshAfterWrite(context.refresh.timeNanos(), TimeUnit.NANOSECONDS); } if (context.expires() || context.refreshes()) { builder.ticker(context.ticker()); } if (context.keyStrength == ReferenceType.WEAK) { builder.weakKeys(); } else if (context.keyStrength == ReferenceType.SOFT) { throw new IllegalStateException(); } if (context.valueStrength == ReferenceType.WEAK) { builder.weakValues(); } else if (context.valueStrength == ReferenceType.SOFT) { builder.softValues(); } if (context.removalListenerType != Listener.DEFAULT) { boolean translateZeroExpire = (context.afterAccess == Expire.IMMEDIATELY) || (context.afterWrite == Expire.IMMEDIATELY); builder.removalListener(new GuavaRemovalListener<>(translateZeroExpire, context.removalListener)); } Ticker ticker = (context.ticker == null) ? Ticker.systemTicker() : context.ticker; if (context.loader == null) { context.cache = new GuavaCache<>(builder.<Integer, Integer>build(), ticker, context.isRecordingStats()); } else if (context.loader().isBulk()) { context.cache = new GuavaLoadingCache<>( builder.build(new BulkLoader<Integer, Integer>(context.loader())), ticker, context.isRecordingStats()); } else { context.cache = new GuavaLoadingCache<>( builder.build(new SingleLoader<Integer, Integer>(context.loader())), ticker, context.isRecordingStats()); } @SuppressWarnings("unchecked") Cache<K, V> castedCache = (Cache<K, V>) context.cache; return castedCache; }
From source file:io.datty.unit.UnitSet.java
protected UnitSet(UnitDattyManager parent, String setName, Properties props) { this.parent = parent; this.name = setName; this.props = props; String ttlSeconds = props.getProperty(UnitPropertyKeys.MAX_ENTRIES); String maxEntries = props.getProperty(UnitPropertyKeys.MAX_ENTRIES); if (maxEntries != null) { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); try {/*from w ww.ja v a 2 s . com*/ builder.maximumSize(Integer.parseInt(maxEntries)); } catch (NumberFormatException e) { throw new DattyException( "invalid property maxEntries in set: " + setName + ", value=" + maxEntries); } if (ttlSeconds != null) { try { builder.expireAfterWrite(Integer.parseInt(ttlSeconds), TimeUnit.SECONDS); } catch (NumberFormatException e) { throw new DattyException( "invalid property maxEntries in cache: " + setName + ", value=" + maxEntries); } } this.backingCache = builder.build(); this.recordMap = backingCache.asMap(); } else { this.backingCache = null; this.recordMap = new ConcurrentHashMap<String, UnitRecord>(); } }
From source file:com.hazelcast.client.MapClientProxy.java
private LoadingCache buildGuavaCache(NearCacheConfig nc) { CacheBuilder cacheBuilder = CacheBuilder.newBuilder().maximumSize(nc.getMaxSize()); if (nc.getTimeToLiveSeconds() > 0) cacheBuilder.expireAfterWrite(nc.getTimeToLiveSeconds(), TimeUnit.SECONDS); if (nc.getMaxIdleSeconds() > 0) cacheBuilder.expireAfterAccess(nc.getMaxIdleSeconds(), TimeUnit.SECONDS); return cacheBuilder.build(new CacheLoader() { @Override//from w w w . ja v a2s.c om public Object load(Object o) throws Exception { try { return MapClientProxy.this.get0(o); } catch (Exception e) { throw new ExecutionException(e); } } }); }
From source file:com.vsct.dt.hesperides.util.HesperidesCacheBuilder.java
/** * Create cache with easy setup./* w ww . j av a 2 s . c om*/ * * @param config setup * @param weigher Guava weighter * * @return cache */ public static CacheBuilder<Object, Object> newBuilder(final HesperidesCacheParameter config, final Weigher<? extends Object, ? extends Object> weigher) { final CacheBuilder<Object, Object> cache = CacheBuilder.newBuilder(); if (config != null) { final int maxSize = config.getMaxSize(); final int weight = config.getWeight(); final String expire = config.getItemExpireAfter(); if (maxSize != HesperidesCacheParameter.NOT_SET) { cache.maximumSize(maxSize); } if (weight != HesperidesCacheParameter.NOT_SET) { if (weigher == null) { throw new IllegalArgumentException("Parameter 'weight' is not supported for this cache."); } cache.maximumWeight(weight); } if (expire != null) { final Pattern p = Pattern.compile("^([0-9]+)(m|s|h|d)"); final Matcher m = p.matcher(expire); if (m.find()) { final int time = Integer.valueOf(m.group(1)); TimeUnit unit = TimeUnit.SECONDS; switch (m.group(2)) { case "m": unit = TimeUnit.MINUTES; break; case "h": unit = TimeUnit.HOURS; break; case "d": unit = TimeUnit.DAYS; break; default: // Nothing } cache.expireAfterWrite(time, unit); cache.expireAfterAccess(time, unit); } else { throw new IllegalArgumentException( "Parameter 'itemExpireAfter' is not valid. Valid usage is [0-9]+(m|h|d|s). (Where 'm' is minutes, 'h' is hours, 'd' is days, 's' seconds."); } } } return cache; }