List of usage examples for com.google.common.cache CacheBuilder expireAfterAccess
public CacheBuilder<K, V> expireAfterAccess(long duration, TimeUnit unit)
From source file:org.opendaylight.controller.cluster.messaging.MessageSlicer.java
MessageSlicer(final Builder builder) { this.fileBackedStreamFactory = builder.fileBackedStreamFactory; this.messageSliceSize = builder.messageSliceSize; this.maxSlicingTries = builder.maxSlicingTries; id = SLICER_ID_COUNTER.getAndIncrement(); this.logContext = builder.logContext + "_slicer-id-" + id; CacheBuilder<Identifier, SlicedMessageState<ActorRef>> cacheBuilder = CacheBuilder.newBuilder() .removalListener(notification -> stateRemoved(notification)); if (builder.expireStateAfterInactivityDuration > 0) { cacheBuilder = cacheBuilder.expireAfterAccess(builder.expireStateAfterInactivityDuration, builder.expireStateAfterInactivityUnit); }//www.j ava2 s . c o m stateCache = cacheBuilder.build(); }
From source file:com.vsct.dt.hesperides.util.HesperidesCacheBuilder.java
/** * Create cache with easy setup./* w ww .jav a 2 s . co m*/ * * @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; }
From source file:org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache.java
@Inject public IndicesFieldDataCache(Settings settings, IndicesFieldDataCacheListener indicesFieldDataCacheListener) { super(settings); this.indicesFieldDataCacheListener = indicesFieldDataCacheListener; String size = componentSettings.get("size", "-1"); long sizeInBytes = componentSettings.getAsMemory("size", "-1").bytes(); if (sizeInBytes > ByteSizeValue.MAX_GUAVA_CACHE_SIZE.bytes()) { logger.warn("reducing requested field data cache size of [{}] to the maximum allowed size of [{}]", new ByteSizeValue(sizeInBytes), ByteSizeValue.MAX_GUAVA_CACHE_SIZE); sizeInBytes = ByteSizeValue.MAX_GUAVA_CACHE_SIZE.bytes(); size = ByteSizeValue.MAX_GUAVA_CACHE_SIZE.toString(); }/*from w w w .j a v a2s. co m*/ final TimeValue expire = componentSettings.getAsTime("expire", null); CacheBuilder<Key, RamUsage> cacheBuilder = CacheBuilder.newBuilder().removalListener(this); if (sizeInBytes > 0) { cacheBuilder.maximumWeight(sizeInBytes).weigher(new FieldDataWeigher()); } // defaults to 4, but this is a busy map for all indices, increase it a bit cacheBuilder.concurrencyLevel(16); if (expire != null && expire.millis() > 0) { cacheBuilder.expireAfterAccess(expire.millis(), TimeUnit.MILLISECONDS); } logger.debug("using size [{}] [{}], expire [{}]", size, new ByteSizeValue(sizeInBytes), expire); cache = cacheBuilder.build(); }
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 www . ja v a 2s . c o m*/ public Object load(Object o) throws Exception { try { return MapClientProxy.this.get0(o); } catch (Exception e) { throw new ExecutionException(e); } } }); }
From source file:it.unibo.alchemist.model.implementations.environments.OSMEnvironment.java
@Override public Route<GeoPosition> computeRoute(final Position p1, final Position p2, final Vehicle vehicle) { if (routecache == null) { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); if (benchmarking) { builder = builder.recordStats(); }//from w ww . j a va2 s .c o m routecache = builder.expireAfterAccess(10, TimeUnit.SECONDS) .build(new CacheLoader<CacheEntry, Route<GeoPosition>>() { @Override public Route<GeoPosition> load(final CacheEntry key) { final Vehicle vehicle = key.v; final Position p1 = key.start; final Position p2 = key.end; final GHRequest req = new GHRequest(p1.getCoordinate(1), p1.getCoordinate(0), p2.getCoordinate(1), p2.getCoordinate(0)).setAlgorithm(DEFAULT_ALGORITHM) .setVehicle(vehicle.toString()).setWeighting(ROUTING_STRATEGY); mapLock.read(); final GraphHopperAPI gh = navigators.get(vehicle); mapLock.release(); if (gh != null) { final GHResponse resp = gh.route(req); return new GraphHopperRoute(resp); } throw new IllegalStateException("Something went wrong while evaluating a route."); } }); } try { return routecache.get(new CacheEntry(vehicle, p1, p2)); } catch (ExecutionException e) { L.error("", e); throw new IllegalStateException("The navigator was unable to compute a route from " + p1 + " to " + p2 + " using the navigator " + vehicle + ". This is most likely a bug", e); } }
From source file:org.graylog2.lookup.caches.GuavaLookupCache.java
@Inject public GuavaLookupCache(@Assisted("id") String id, @Assisted("name") String name, @Assisted LookupCacheConfiguration c, @Named("processbuffer_processors") int processorCount, MetricRegistry metricRegistry) { super(id, name, c, metricRegistry); Config config = (Config) c;/*from w w w.j ava2 s .c o m*/ CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); // the theory is that typically only processors will affect the cache concurrency, whereas decorator usage is less critical builder.concurrencyLevel(processorCount).recordStats(); builder.maximumSize(config.maxSize()); if (config.expireAfterAccess() > 0 && config.expireAfterAccessUnit() != null) { //noinspection ConstantConditions builder.expireAfterAccess(config.expireAfterAccess(), config.expireAfterAccessUnit()); } if (config.expireAfterWrite() > 0 && config.expireAfterWriteUnit() != null) { //noinspection ConstantConditions builder.expireAfterWrite(config.expireAfterWrite(), config.expireAfterWriteUnit()); } cache = new InstrumentedCache<>(builder.build(), this); }
From source file:org.apache.hedwig.server.topics.AbstractTopicManager.java
public AbstractTopicManager(ServerConfiguration cfg, ScheduledExecutorService scheduler) throws UnknownHostException { this.cfg = cfg; this.queuer = new TopicOpQueuer(scheduler); this.scheduler = scheduler; addr = cfg.getServerAddr();//from w w w . java 2 s. c om // build the topic cache CacheBuilder<ByteString, TopicStats> cacheBuilder = CacheBuilder.newBuilder() .maximumSize(cfg.getMaxNumTopics()).initialCapacity(cfg.getInitNumTopics()) // TODO: change to same number as topic op queuer threads .concurrencyLevel(Runtime.getRuntime().availableProcessors()) .removalListener(new ReleaseTopicListener()); if (cfg.getRetentionSecsAfterAccess() > 0) { cacheBuilder.expireAfterAccess(cfg.getRetentionSecsAfterAccess(), TimeUnit.SECONDS); } topics = cacheBuilder.build(); }
From source file:org.elasticsearch.indices.cache.request.IndicesRequestCache.java
private void buildCache() { long sizeInBytes = MemorySizeValue.parseBytesSizeValueOrHeapRatio(size, INDICES_CACHE_QUERY_SIZE).bytes(); CacheBuilder<Key, Value> cacheBuilder = CacheBuilder.newBuilder().maximumWeight(sizeInBytes) .weigher(new QueryCacheWeigher()).removalListener(this); cacheBuilder.concurrencyLevel(concurrencyLevel); if (expire != null) { cacheBuilder.expireAfterAccess(expire.millis(), TimeUnit.MILLISECONDS); }// w w w . java 2 s . c o m cache = cacheBuilder.build(); }
From source file:org.elasticsearch.indices.cache.query.IndicesQueryCache.java
private void buildCache() { long sizeInBytes = MemorySizeValue.parseBytesSizeValueOrHeapRatio(size).bytes(); CacheBuilder<Key, BytesReference> cacheBuilder = CacheBuilder.newBuilder().maximumWeight(sizeInBytes) .weigher(new QueryCacheWeigher()).removalListener(this); cacheBuilder.concurrencyLevel(concurrencyLevel); if (expire != null) { cacheBuilder.expireAfterAccess(expire.millis(), TimeUnit.MILLISECONDS); }//from w w w . j a v a 2 s .c om cache = cacheBuilder.build(); }
From source file:com.streamsets.pipeline.stage.processor.kv.LookupProcessor.java
private LoadingCache<String, Optional<String>> buildCache() { CacheBuilder build = CacheBuilder.newBuilder(); if (!conf.cache.enabled) { return build.maximumSize(0).build(new StoreCacheLoader(store)); }//from w ww . ja va 2 s . c o m // CacheBuilder doesn't support specifying type thus suffers from erasure, so // we build it with this if / else logic. if (conf.cache.maxSize == -1) { conf.cache.maxSize = Long.MAX_VALUE; } build.maximumSize(conf.cache.maxSize); if (conf.cache.evictionPolicyType == EvictionPolicyType.EXPIRE_AFTER_ACCESS) { build.expireAfterAccess(conf.cache.expirationTime, conf.cache.timeUnit); } else if (conf.cache.evictionPolicyType == EvictionPolicyType.EXPIRE_AFTER_WRITE) { build.expireAfterWrite(conf.cache.expirationTime, conf.cache.timeUnit); } else { throw new IllegalArgumentException( Utils.format("Unrecognized EvictionPolicyType: '{}'", conf.cache.evictionPolicyType)); } return build.build(new StoreCacheLoader(store)); }