Example usage for com.google.common.cache CacheBuilder removalListener

List of usage examples for com.google.common.cache CacheBuilder removalListener

Introduction

In this page you can find the example usage for com.google.common.cache CacheBuilder removalListener.

Prototype

RemovalListener removalListener

To view the source code for com.google.common.cache CacheBuilder removalListener.

Click Source Link

Usage

From source file:ratpack.session.SessionModule.java

/**
 * A builder for an alternative cache for the default in memory store.
 * <p>/*  w w  w  . j  a  va  2  s . c o  m*/
 * This method can be used from within a custom {@link Module}.
 * <pre class="java">{@code
 * import com.google.inject.AbstractModule;
 * import ratpack.session.SessionModule;
 *
 * public class CustomSessionModule extends AbstractModule {
 *   protected void configure() {
 *     SessionModule.memoryStore(binder(), c -> c.maximumSize(100));
 *   }
 * }
 * }</pre>
 * }<p>
 * This method binds the built cache with the {@link #LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY} key.
 * It also implicitly registers a {@link RemovalListener}, that releases the byte buffers as they are discarded.
 *
 * @param binder the guice binder
 * @param config the cache configuration
 */
public static void memoryStore(Binder binder, Consumer<? super CacheBuilder<AsciiString, ByteBuf>> config) {
    binder.bind(LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY).toProvider(() -> {
        CacheBuilder<AsciiString, ByteBuf> cacheBuilder = Types.cast(CacheBuilder.newBuilder());
        cacheBuilder.removalListener(n -> n.getValue().release());
        config.accept(cacheBuilder);
        return cacheBuilder.build();
    }).in(Scopes.SINGLETON);
}

From source file:org.locationtech.geogig.storage.cache.SharedCache.java

@VisibleForTesting
static SharedCache build(int L1capacity, long maxCacheSizeBytes) {
    checkArgument(L1capacity >= 0);/*from  w w  w .  j  a v a 2 s.c o  m*/
    checkArgument(maxCacheSizeBytes >= 0, "Cache size can't be < 0, 0 meaning no cache at all");

    if (0L == maxCacheSizeBytes) {
        return NO_CACHE;
    }

    int initialCapacityCount = 1_000_000;
    int concurrencyLevel = 16;

    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    cacheBuilder = cacheBuilder.maximumWeight(maxCacheSizeBytes);
    cacheBuilder.weigher(Impl.SizeTracker.WEIGHER);

    cacheBuilder.initialCapacity(initialCapacityCount);
    cacheBuilder.concurrencyLevel(concurrencyLevel);
    cacheBuilder.recordStats();

    Impl.SizeTracker sizeTracker = new Impl.SizeTracker();
    cacheBuilder.removalListener(sizeTracker);

    Cache<Key, byte[]> byteCache = cacheBuilder.build();

    return new Impl(L1capacity, byteCache, sizeTracker);
}

From source file:org.locationtech.geogig.storage.postgresql.PGCache.java

private static PGCache build(Integer initialCapacityCount, Integer concurrencyLevel2, Long maxWeightBytes,
        Optional<Integer> expireSeconds) {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    cacheBuilder = cacheBuilder.maximumWeight(maxWeightBytes);
    cacheBuilder.weigher(weigher);/*from  w ww  .  j  a  v  a  2s  .  co  m*/
    if (expireSeconds.isPresent()) {
        long seconds = expireSeconds.get();
        Preconditions.checkArgument(seconds > -1);
        cacheBuilder.expireAfterAccess(seconds, TimeUnit.SECONDS);
    }
    cacheBuilder.initialCapacity(initialCapacityCount);
    cacheBuilder.concurrencyLevel(concurrencyLevel2);
    cacheBuilder.recordStats();

    SizeTracker sizeTracker = new SizeTracker();
    cacheBuilder.removalListener(sizeTracker);

    Cache<ObjectId, byte[]> byteCache = cacheBuilder.build();

    return new PGCache(byteCache, sizeTracker);
}

From source file:com.torodb.mongowp.bson.netty.pool.GuavaStringPool.java

@Inject
public GuavaStringPool(StringPoolPolicy heuristic, CacheBuilder<Object, Object> cacheBuilder) {
    super(heuristic);
    cache = cacheBuilder.removalListener(new MyRemovalListener()).build(new MyCacheLoader());
}

From source file:org.objectfabric.GoogleCache.java

@SuppressWarnings("unchecked")
public GoogleCache(CacheBuilder builder) {
    super(true, new GoogleCacheBackend(builder.build().asMap()));

    builder.removalListener(new RemovalListener() {

        @Override//from w  w  w . ja v a2s .  co m
        public void onRemoval(RemovalNotification notification) {
            onEviction(notification.getValue());
        }
    });
}

From source file:com.streamsets.pipeline.lib.parser.net.netflow.v9.NetflowV9Decoder.java

public static Cache<FlowSetTemplateCacheKey, FlowSetTemplate> buildTemplateCache(int maxTemplateCacheSize,
        int templateCacheTimeoutMs) {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    if (maxTemplateCacheSize > 0) {
        cacheBuilder = cacheBuilder.maximumSize(maxTemplateCacheSize);
    }//from  www .j av a 2 s  .co  m
    if (templateCacheTimeoutMs > 0) {
        cacheBuilder = cacheBuilder.expireAfterAccess(templateCacheTimeoutMs, TimeUnit.MILLISECONDS);
    }
    if (LOG.isTraceEnabled()) {
        cacheBuilder = cacheBuilder.removalListener(
                (notification) -> LOG.trace("Removing flow set template entry {} for cause: {} ",
                        notification.getKey(), notification.getCause()));
    }
    return cacheBuilder.build();
}

From source file:com.streamsets.pipeline.lib.jdbc.PreparedStatementCache.java

PreparedStatementCache(Connection connection, String tableName,
        List<JdbcFieldColumnMapping> generatedColumnMappings, List<String> primaryKeyColumns, int opCode,
        int maxCacheSize, boolean caseSensitive) {
    this.jdbcUtil = UtilsProvider.getJdbcUtil();
    this.connection = connection;
    this.tableName = tableName;
    this.generatedColumnMappings = generatedColumnMappings;
    this.primaryKeyColumns = primaryKeyColumns;
    this.opCode = opCode;
    this.caseSensitive = caseSensitive;

    CacheBuilder cacheBuilder = CacheBuilder.newBuilder();
    if (maxCacheSize > -1) {
        cacheBuilder.maximumSize(maxCacheSize);
    }// www. j  a v a  2  s.c o  m

    cacheMap = cacheBuilder.removalListener(new PreparedStatementRemovalListener())
            .build(new PreparedStatementLoader());
}

From source file:com.davidbracewell.cache.impl.GuavaCache.java

/**
 * Default Constructor/*from w w  w . j a  v  a 2 s.  c o m*/
 *
 * @param specification The cache specification
 */
public GuavaCache(CacheSpec<K, V> specification) {
    super(Preconditions.checkNotNull(specification));
    CacheBuilder<K, V> cacheBuilder = GuavaCacheUtils.cacheBuilderFromSpec(specification);
    if (specification.getRemovalListener() == null) {
        this.cache = cacheBuilder.build();
    } else {
        this.cache = cacheBuilder.removalListener(specification.getRemovalListener()).build();
    }
}

From source file:com.google.gerrit.server.cache.h2.DefaultCacheFactory.java

@SuppressWarnings("unchecked")
<K, V> CacheBuilder<K, V> create(CacheBinding<K, V> def, boolean unwrapValueHolder) {
    CacheBuilder<K, V> builder = newCacheBuilder();
    builder.recordStats();//  www . j ava2  s.co m
    builder.maximumWeight(cfg.getLong("cache", def.name(), "memoryLimit", def.maximumWeight()));

    builder.removalListener(forwardingRemovalListenerFactory.create(def.name()));

    Weigher<K, V> weigher = def.weigher();
    if (weigher != null && unwrapValueHolder) {
        final Weigher<K, V> impl = weigher;
        weigher = (Weigher<K, V>) new Weigher<K, ValueHolder<V>>() {
            @Override
            public int weigh(K key, ValueHolder<V> value) {
                return impl.weigh(key, value.value);
            }
        };
    } else if (weigher == null) {
        weigher = unitWeight();
    }
    builder.weigher(weigher);

    Long age = def.expireAfterWrite(TimeUnit.SECONDS);
    if (has(def.name(), "maxAge")) {
        builder.expireAfterWrite(ConfigUtil.getTimeUnit(cfg, "cache", def.name(), "maxAge",
                age != null ? age : 0, TimeUnit.SECONDS), TimeUnit.SECONDS);
    } else if (age != null) {
        builder.expireAfterWrite(age, TimeUnit.SECONDS);
    }

    return builder;
}

From source file:net.voxton.mafiacraft.core.player.PlayerManager.java

/**
 * Creates the player cache./*  w  ww .  j  av  a2 s .  com*/
 */
private void buildCache() {
    CacheBuilder builder = CacheBuilder.newBuilder();

    builder.maximumSize(10000).expireAfterWrite(10, TimeUnit.MINUTES);

    builder.removalListener(new RemovalListener<String, MPlayer>() {

        @Override
        public void onRemoval(RemovalNotification<String, MPlayer> rn) {
            savePlayer(rn.getValue());
        }

    });

    players = builder.build(new CacheLoader<String, MPlayer>() {

        @Override
        public MPlayer load(String key) throws Exception {
            return loadPlayer(key);
        }

    });
}