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

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

Introduction

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

Prototype

@GwtIncompatible("java.lang.ref.SoftReference")
public CacheBuilder<K, V> softValues() 

Source Link

Document

Specifies that each value (not key) stored in the cache should be wrapped in a SoftReference (by default, strong references are used).

Usage

From source file:org.locationtech.geogig.di.caching.CacheFactory.java

protected synchronized void createCache() {
    if (cache != null) {
        return;/* w  w  w  . ja va2 s.  c om*/
    }
    if (!cacheIsEnabled()) {
        this.cache = NO_CACHE;
        return;
    }
    final int maxSize = getConfig("maxSize", 50_000);
    final int concurrencyLevel = getConfig("concurrencyLevel", 4);

    final int expireSeconds = getConfig("expireSeconds", 300);
    final int initialCapacity = getConfig("initialCapacity", 10 * 1000);
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    cacheBuilder = cacheBuilder.maximumSize(maxSize);
    cacheBuilder.expireAfterAccess(expireSeconds, TimeUnit.SECONDS);
    cacheBuilder.initialCapacity(initialCapacity);
    cacheBuilder.concurrencyLevel(concurrencyLevel);
    cacheBuilder.softValues();

    try {
        this.cache = cacheBuilder.build();
    } catch (RuntimeException e) {
        LOGGER.error(
                "Error configuring cache '{}' with maxSize: {}, expireSeconds: {}, initialCapacity: {}, concurrencyLevel: {}",
                configKeywordPrefix, maxSize, expireSeconds, initialCapacity, concurrencyLevel, e);

        throw e;
    }

    LOGGER.debug(
            "Cache '{}' configured with maxSize: {}, expireSeconds: {}, initialCapacity: {}, concurrencyLevel: {}",
            configKeywordPrefix, maxSize, expireSeconds, initialCapacity, concurrencyLevel);

}

From source file:org.apache.hadoop.hive.ql.io.orc.LocalCache.java

LocalCache(int numThreads, long cacheMemSize, boolean useSoftRef) {
    CacheBuilder<Path, TailAndFileData> builder = CacheBuilder.newBuilder()
            .initialCapacity(DEFAULT_CACHE_INITIAL_CAPACITY).concurrencyLevel(numThreads)
            .maximumWeight(cacheMemSize).weigher(new Weigher<Path, TailAndFileData>() {
                @Override/*from  w  ww . j ava2s .com*/
                public int weigh(Path key, TailAndFileData value) {
                    return value.getMemoryUsage();
                }
            });

    if (useSoftRef) {
        builder = builder.softValues();
    }
    cache = builder.build();
}

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  a2  s .  c  o 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:uk.q3c.krail.core.user.opt.GuavaCacheConfiguration.java

public CacheBuilder<Object, Object> builder() {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    if (initialCapacity != null) {
        builder.initialCapacity(initialCapacity);
    }/*from  w  w  w.jav a2 s  .  com*/
    if (maximumSize != null) {
        builder.maximumSize(maximumSize);
    }
    if (maximumWeight != null) {
        builder.maximumWeight(maximumWeight);
    }
    if (concurrencyLevel != null) {
        builder.concurrencyLevel(concurrencyLevel);
    }
    if (weakKeys) {
        builder.weakKeys();
    }

    if (weakValues) {
    }
    builder.weakValues();
    if (softValues) {
        builder.softValues();
    }

    if (expireAfterWriteDuration != null) {
        builder.expireAfterWrite(expireAfterWriteDuration, expireAfterWriteTimeUnit);
    }
    if (expireAfterAccessDuration != null) {
        builder.expireAfterAccess(expireAfterAccessDuration, expireAfterAccessTimeUnit);
    }
    if (refreshAfterWriteDuration != null) {
        builder.refreshAfterWrite(refreshAfterWriteDuration, refreshAfterWriteTimeUnit);
    }

    if (ticker != null) {
        builder.ticker(ticker);
    }

    if (removalListener != null) {
        builder.removalListener(removalListener);
    }

    if (recordStats) {
        builder.recordStats();
    }
    return builder;
}

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 av a 2 s  .  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: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 w  w  .j  av a 2  s.co  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:org.apache.kylin.dict.CachedTreeMap.java

private CachedTreeMap(int maxCount, Class<K> keyClazz, Class<V> valueClazz, String basePath, boolean immutable,
        int maxVersions, long versionTTL) throws IOException {
    super();/*from w  w w  .  j a v a  2s. c o m*/
    this.keyClazz = keyClazz;
    this.valueClazz = valueClazz;
    this.immutable = immutable;
    this.keepAppend = true;
    this.maxVersions = maxVersions;
    this.versionTTL = versionTTL;
    this.conf = new Configuration();
    if (basePath.endsWith("/")) {
        basePath = basePath.substring(0, basePath.length() - 1);
    }
    this.baseDir = new Path(basePath);
    this.fs = FileSystem.get(baseDir.toUri(), conf);
    if (!fs.exists(baseDir)) {
        fs.mkdirs(baseDir);
    }
    this.versionDir = getLatestVersion(conf, fs, baseDir);
    this.workingDir = new Path(baseDir, "working");
    if (!this.immutable) {
        // For mutable map, copy all data into working dir and work on it, avoiding suddenly server crash made data corrupt
        if (fs.exists(workingDir)) {
            fs.delete(workingDir, true);
        }
        FileUtil.copy(fs, versionDir, fs, workingDir, false, true, conf);
    }
    CacheBuilder builder = CacheBuilder.newBuilder().removalListener(new RemovalListener<K, V>() {
        @Override
        public void onRemoval(RemovalNotification<K, V> notification) {
            logger.info(String.format("Evict cache key %s(%d) with value %s caused by %s, size %d/%d ",
                    notification.getKey(), notification.getKey().hashCode(), notification.getValue(),
                    notification.getCause(), size(), valueCache.size()));
            switch (notification.getCause()) {
            case SIZE:
                writeValue(notification.getKey(), notification.getValue());
                break;
            case EXPLICIT:
                deleteValue(notification.getKey());
                break;
            default:
            }
        }
    });
    if (this.immutable) {
        // For immutable values, load all values as much as possible, and evict by soft reference to free memory when gc
        builder.softValues();
    } else {
        builder.maximumSize(maxCount);
    }
    this.valueCache = builder.build(new CacheLoader<K, V>() {
        @Override
        public V load(K key) throws Exception {
            V value = readValue(key);
            logger.info(String.format("Load cache by key %s(%d) with value %s", key, key.hashCode(), value));
            return value;
        }
    });
}

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);
    }//from w w  w .j a v  a  2  s .  com
    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);
    }// ww w .  ja  va  2  s  . c  o m
    if (softValues) {
        mapMaker.softValues();
    }

    //noinspection unchecked
    return mapMaker.build().asMap();
}