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

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

Introduction

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

Prototype

@GwtIncompatible("To be supported (synchronously).")
public CacheBuilder<K, V> refreshAfterWrite(long duration, TimeUnit unit) 

Source Link

Document

Specifies that active entries are eligible for automatic refresh once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.

Usage

From source file:io.prestosql.plugin.hive.metastore.CachingHiveMetastore.java

private static CacheBuilder<Object, Object> newCacheBuilder(OptionalLong expiresAfterWriteMillis,
        OptionalLong refreshMillis, long maximumSize) {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    if (expiresAfterWriteMillis.isPresent()) {
        cacheBuilder = cacheBuilder.expireAfterWrite(expiresAfterWriteMillis.getAsLong(), MILLISECONDS);
    }//ww w .  java2 s .  c o  m
    if (refreshMillis.isPresent() && (!expiresAfterWriteMillis.isPresent()
            || expiresAfterWriteMillis.getAsLong() > refreshMillis.getAsLong())) {
        cacheBuilder = cacheBuilder.refreshAfterWrite(refreshMillis.getAsLong(), MILLISECONDS);
    }
    cacheBuilder = cacheBuilder.maximumSize(maximumSize);
    return cacheBuilder;
}

From source file:com.addthis.hydra.job.store.AvailableCache.java

/**
 * Make a cache using specified cache parameters
 *
 * @param refreshMillis How frequently values should be refreshed in milliseconds (if <= 0, no refresh)
 * @param expireMillis  How old values should have to be before they are expired (if <= 0, they never expire)
 * @param maxSize       How many values should be stored in the cache (if <= 0, no explicit limit)
 * @param fetchThreads  How many threads to use to fetch values in the background (if <=0, use two threads)
 *//* ww  w  .  j  a v a2s . c  om*/
public AvailableCache(long refreshMillis, long expireMillis, int maxSize, int fetchThreads) {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    // Configure the cache for any parameters that are > 0
    if (expireMillis > 0) {
        cacheBuilder.expireAfterWrite(expireMillis, TimeUnit.MILLISECONDS);
    }
    if (refreshMillis > 0) {
        cacheBuilder.refreshAfterWrite(refreshMillis, TimeUnit.MILLISECONDS);
    }
    if (maxSize > 0) {
        cacheBuilder.maximumSize(maxSize);
    }
    if (fetchThreads <= 0) {
        fetchThreads = 2;
    }
    executor = new ThreadPoolExecutor(fetchThreads, fetchThreads, 1000L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(),
            new ThreadFactoryBuilder().setNameFormat("avail-cache-%d").setDaemon(true).build());
    //noinspection unchecked
    this.loadingCache = cacheBuilder.build(new CacheLoader<String, Optional<T>>() {
        @Override
        /**
         * If refreshAfterWrite is enabled, this method is called after returning the old value.
         * The new value will be inserted into the cache when the load() operation completes.
         */
        public ListenableFuture<Optional<T>> reload(final String key, Optional<T> oldValue) {
            ListenableFutureTask<Optional<T>> task = ListenableFutureTask.create(() -> load(key));
            executor.execute(task);
            return task;
        }

        @Override
        public Optional<T> load(String key) throws Exception {
            return Optional.fromNullable(fetchValue(key));
        }
    });
}

From source file:org.apache.nifi.minifi.c2.service.ConfigService.java

public ConfigService(List<ConfigurationProvider> configurationProviders, Authorizer authorizer,
        long maximumCacheSize, long cacheTtlMillis) {
    this.authorizer = authorizer;
    this.objectMapper = new ObjectMapper();
    if (configurationProviders == null || configurationProviders.size() == 0) {
        throw new IllegalArgumentException("Expected at least one configuration provider");
    }/* w  w w .  j a  v  a2  s. c  o m*/
    this.configurationProviderInfo = Suppliers.memoizeWithExpiration(
            () -> initContentTypeInfo(configurationProviders), cacheTtlMillis, TimeUnit.MILLISECONDS);
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    if (maximumCacheSize >= 0) {
        cacheBuilder = cacheBuilder.maximumSize(maximumCacheSize);
    }
    if (cacheTtlMillis >= 0) {
        cacheBuilder = cacheBuilder.refreshAfterWrite(cacheTtlMillis, TimeUnit.MILLISECONDS);
    }
    this.configurationCache = cacheBuilder
            .build(new CacheLoader<ConfigurationProviderKey, ConfigurationProviderValue>() {
                @Override
                public ConfigurationProviderValue load(ConfigurationProviderKey key) throws Exception {
                    return initConfigurationProviderValue(key);
                }
            });
}

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());
    }/* w  ww. j  a v  a 2  s . c  om*/
    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  ww  w. j a v a2  s . 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:org.eclipse.osee.cache.admin.internal.CacheFactory.java

private CacheBuilder<Object, Object> createCacheBuilder(CacheConfiguration config) {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    if (config.hasInitialCapacity()) {
        builder = builder.initialCapacity(config.getInitialCapacity());
    }/*from  ww  w.  ja va  2  s . co m*/
    if (config.hasMaximumSize()) {
        builder = builder.maximumSize(config.getMaximumSize());
    }
    if (config.isExpireAfterAccess()) {
        Pair<Long, TimeUnit> data = config.getExpireAfterAccess();
        builder = builder.expireAfterAccess(data.getFirst(), data.getSecond());
    }
    if (config.isExpireAfterWrite()) {
        Pair<Long, TimeUnit> data = config.getExpireAfterWrite();
        builder = builder.expireAfterWrite(data.getFirst(), data.getSecond());
    }
    if (config.isRefreshAfterWrite()) {
        Pair<Long, TimeUnit> data = config.getRefreshAfterWrite();
        builder = builder.refreshAfterWrite(data.getFirst(), data.getSecond());
    }
    return builder;
}

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);
    }/*  www  . j  a v  a2s  .co m*/
    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:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestResourceServiceImpl.java

protected LoadingCache<String, Sardine> buildSardineCache() {
    CacheProperties cacheProperties = properties.getResourceService().getSardineCache();
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    if (cacheProperties.getConcurrencyLevel() != null) {
        builder.concurrencyLevel(cacheProperties.getConcurrencyLevel());
    }//from ww w  .j  a  v  a  2 s.co  m
    if (cacheProperties.getExpireAfterAccess() != null
            && cacheProperties.getExpireAfterAccessTimeUnit() != null) {
        builder.expireAfterAccess(cacheProperties.getExpireAfterAccess(),
                cacheProperties.getExpireAfterAccessTimeUnit());
    }
    if (cacheProperties.getExpireAfterWrite() != null
            && cacheProperties.getExpireAfterWriteTimeUnit() != null) {
        builder.expireAfterWrite(cacheProperties.getExpireAfterWrite(),
                cacheProperties.getExpireAfterWriteTimeUnit());
    }
    if (cacheProperties.getInitialCapacity() != null) {
        builder.initialCapacity(cacheProperties.getInitialCapacity());
    }
    if (cacheProperties.getMaximumSize() != null) {
        builder.maximumSize(cacheProperties.getMaximumSize());
    }
    if (cacheProperties.getMaximumWeight() != null) {
        builder.maximumWeight(cacheProperties.getMaximumWeight());
    }
    if (cacheProperties.getRefreshAfterWrite() != null
            && cacheProperties.getRefreshAfterWriteTimeUnit() != null) {
        builder.refreshAfterWrite(cacheProperties.getRefreshAfterWrite(),
                cacheProperties.getRefreshAfterWriteTimeUnit());
    }
    return builder.build(sardineCacheLoader);
}