List of usage examples for com.google.common.cache CacheBuilder removalListener
RemovalListener removalListener
To view the source code for com.google.common.cache CacheBuilder removalListener.
Click Source Link
From source file:com.heliosapm.jmx.cache.CacheStatistics.java
/** * Creates a new CacheStatistics and the underlying cache from the passed {@link CacheBuilder}. * This call causes this CacheStatistics to register itself as the cache's removal listener * and removal events are broadcast as JMX notifications. * @param builder The guava cache builder * @param cacheName The assigned name for this cache *///from w w w. j a v a2 s. co m public CacheStatistics(final CacheBuilder<K, V> builder, final String cacheName) { super(SharedNotificationExecutor.getInstance(), notificationInfos); builder.removalListener(this); this.cache = builder.build(); this.cacheName = cacheName; objectName = JMXHelper.objectName(JMXHelper.objectName("com.heliosapm.cache:name=" + cacheName)); }
From source file:org.trimou.engine.cache.DefaultComputingCacheFactory.java
@Override public <K, V> ComputingCache<K, V> create(final String consumerId, final Function<K, V> computingFunction, final Long expirationTimeout, final Long maxSize, final Listener<K> listener) { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); if (expirationTimeout != null && expirationTimeout > 0) { builder.expireAfterWrite(expirationTimeout, TimeUnit.MILLISECONDS); }//ww w . j a va2s . c o m if (maxSize != null) { builder.maximumSize(maxSize); } if (listener != null) { builder.removalListener(new RemovalListener<K, V>() { @Override public void onRemoval(RemovalNotification<K, V> notification) { listener.entryInvalidated(notification.getKey(), notification.getCause().toString()); } }); } return new LoadingCacheAdapter<K, V>(builder.build(new CacheLoaderAdapter<K, V>(computingFunction))); }
From source file:org.restheart.cache.impl.GuavaCache.java
public GuavaCache(long size, EXPIRE_POLICY expirePolicy, long ttl, Consumer<Map.Entry<K, Optional<V>>> remover) { CacheBuilder builder = CacheBuilder.newBuilder(); builder.maximumSize(size);/*from www . j a v a2 s .c o m*/ if (ttl > 0 && expirePolicy == EXPIRE_POLICY.AFTER_WRITE) { builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS); } else if (ttl > 0 && expirePolicy == EXPIRE_POLICY.AFTER_READ) { builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS); } wrapped = builder.removalListener((RemovalNotification notification) -> { remover.accept(notification); }).build(); }
From source file:com.hortonworks.streamline.storage.impl.jdbc.provider.sql.factory.AbstractQueryExecutor.java
private Cache<SqlQuery, PreparedStatementBuilder> buildCache( CacheBuilder<SqlQuery, PreparedStatementBuilder> cacheBuilder) { return cacheBuilder.removalListener(new RemovalListener<SqlQuery, PreparedStatementBuilder>() { /** Closes and removes the database connection when the entry is removed from cache */ @Override/*from w w w . j a v a 2s. co m*/ public void onRemoval(RemovalNotification<SqlQuery, PreparedStatementBuilder> notification) { final PreparedStatementBuilder val = notification.getValue(); log.debug("Removing entry from cache and closing connection [key:{}, val: {}]", notification.getKey(), val); log.debug("Cache size: {}", cache.size()); if (val != null) { closeConnection(val.getConnection()); } } }).build(); }
From source file:com.davidbracewell.cache.impl.GuavaLoadingCache.java
public GuavaLoadingCache(CacheSpec<K, V> specification) { super(Preconditions.checkNotNull(specification)); Preconditions.checkNotNull(specification.getFunction()); CacheBuilder<K, V> cacheBuilder = GuavaCacheUtils.cacheBuilderFromSpec(specification); CacheLoader<K, V> loader = new CacheLoader<K, V>() { @Override// ww w . j a v a2 s . co m public V load(K key) throws Exception { return function.apply(key); } }; if (specification.getRemovalListener() == null) { this.cache = cacheBuilder.build(loader); } else { this.cache = cacheBuilder.removalListener(specification.getRemovalListener()).build(loader); } }
From source file:com.turbospaces.spaces.SpaceReceiveAdapter.java
@VisibleForTesting Cache<Long, SpaceTransactionHolder> modificationContextFor(final Address address) { Cache<Long, SpaceTransactionHolder> cache = durableTransactions.get(address); if (cache == null) synchronized (this) { CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); applyExpireAfterWriteSettings(cacheBuilder); cache = cacheBuilder.removalListener(new RemovalListener<Long, SpaceTransactionHolder>() { @Override/*from ww w . ja v a 2 s.com*/ public void onRemoval(final RemovalNotification<Long, SpaceTransactionHolder> notification) { Long transactionId = notification.getKey(); SpaceTransactionHolder txHolder = notification.getValue(); if (notification.wasEvicted()) { logger.warn("cleaning up(rolling back) expired transaction id={}", transactionId); jSpace.syncTx(txHolder.getModificationContext(), false); } } }).build(); durableTransactions.putIfAbsent(address, cache); cache = durableTransactions.get(address); } return cache; }
From source file:org.auraframework.impl.cache.CacheImpl.java
public CacheImpl(Builder<K, T> builder) { // if builder.useSecondaryStorage is true, we should try to use a // non-quava secondary-storage cache with streaming ability com.google.common.cache.CacheBuilder<Object, Object> cb = com.google.common.cache.CacheBuilder.newBuilder() .initialCapacity(builder.initialCapacity).maximumSize(builder.maximumSize) .concurrencyLevel(builder.concurrencyLevel); if (builder.recordStats) { cb = cb.recordStats();//from w w w .j a v a2s.co m } if (builder.softValues) { cb = cb.softValues(); } EvictionListener<K, T> listener = new EvictionListener<K, T>(builder.name); cb.removalListener(listener); cache = cb.build(); listener.setCache(cache); }
From source file:com.datastax.driver.core.CodecRegistry.java
private CacheBuilder<CacheKey, TypeCodec<?>> defaultCacheBuilder() { CacheBuilder<CacheKey, TypeCodec<?>> builder = CacheBuilder.newBuilder() // 19 primitive codecs + collections thereof = 19*3 + 19*19 = 418 codecs, // so let's start with roughly 1/4 of that .initialCapacity(100).maximumWeight(1000).weigher(new TypeCodecWeigher()); if (logger.isTraceEnabled()) // do not bother adding a listener if it will be ineffective builder = builder.removalListener(new TypeCodecRemovalListener()); return builder; }
From source file:it.geosolutions.concurrent.ConcurrentTileCacheMultiMap.java
/** Private cache creation method */ private Cache<Object, CachedTileImpl> buildCache() { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); builder.maximumWeight((long) (memoryCacheCapacity * memoryCacheThreshold)) .concurrencyLevel(concurrencyLevel).weigher(new Weigher<Object, CachedTileImpl>() { public int weigh(Object o, CachedTileImpl cti) { return (int) cti.getTileSize(); }// w w w. ja v a 2 s. co m }); // Setting of the listener builder.removalListener(createListener(diagnosticEnabled)); // Enable statistics only when the diagnostic flag is set to true; if (diagnosticEnabled) { builder.recordStats(); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Building Cache"); } // Update of the Memory cache size currentCacheCapacity = new AtomicLong(0); return builder.build(); }
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 . j a v a2 s . co 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; }