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

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

Introduction

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

Prototype

public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) 

Source Link

Document

Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.

Usage

From source file:com.google.api.control.aggregator.ReportAggregationOptions.java

/**
 * Creates a {@link Cache} configured by this instance.
 *
 * @param <T>//from  w  w  w  .j  av a 2  s .c om
 *            the type of the value stored in the Cache
 * @param out
 *            a concurrent {@code Deque} to which cached values are added as
 *            they are removed from the cache
 * @param ticker
 *            the time source used to determine expiration
 * @return a {@link Cache} corresponding to this instance's values or
 *         {@code null} unless {@code #numEntries} is positive.
 */
@Nullable
public <T> Cache<String, T> createCache(final ConcurrentLinkedDeque<T> out, Ticker ticker) {
    Preconditions.checkNotNull(out, "The out deque cannot be null");
    Preconditions.checkNotNull(ticker, "The ticker cannot be null");
    if (numEntries <= 0) {
        return null;
    }
    final RemovalListener<String, T> listener = new RemovalListener<String, T>() {
        @Override
        public void onRemoval(RemovalNotification<String, T> notification) {
            out.addFirst(notification.getValue());
        }
    };
    CacheBuilder<String, T> b = CacheBuilder.newBuilder().maximumSize(numEntries).ticker(ticker)
            .removalListener(listener);
    if (flushCacheEntryIntervalMillis >= 0) {
        b.expireAfterWrite(flushCacheEntryIntervalMillis, TimeUnit.MILLISECONDS);
    }
    return b.build();
}

From source file:me.defying.chili.memoize.MemoizeCacheLoader.java

@Override
public Cache<Object, Optional<Object>> load(Method key) throws Exception {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    Memoize annotation = key.getAnnotation(Memoize.class);

    if (annotation.size() > 0) {
        builder.maximumSize(annotation.size());
    }//  w  ww  . j  a  v a 2 s . co m

    if (annotation.time() > 0) {
        builder.expireAfterWrite(annotation.time(), annotation.unit());
    }

    if (annotation.statistics()) {
        builder.recordStats();
    }

    return builder.build();
}

From source file:com.google.api.control.aggregator.CheckAggregationOptions.java

/**
 * Creates a {@link Cache} configured by this instance.
 *
 * @param <T>/*  w  w  w .ja va  2 s  .  c o m*/
 *            the type of the value stored in the Cache
 * @param out
 *            a concurrent {@code Deque} to which the cached values are
 *            added as they are removed from the cache
 * @param ticker
 *            the time source used to determine expiration
 * @return a {@link Cache} corresponding to this instance's values or
 *         {@code null} unless {@code #numEntries} is positive.
 */
@Nullable
public <T> Cache<String, T> createCache(final ConcurrentLinkedDeque<T> out, Ticker ticker) {
    Preconditions.checkNotNull(out, "The out deque cannot be null");
    Preconditions.checkNotNull(ticker, "The ticker cannot be null");
    if (numEntries <= 0) {
        return null;
    }
    final RemovalListener<String, T> listener = new RemovalListener<String, T>() {
        @Override
        public void onRemoval(RemovalNotification<String, T> notification) {
            out.addFirst(notification.getValue());
        }
    };
    CacheBuilder<String, T> b = CacheBuilder.newBuilder().maximumSize(numEntries).ticker(ticker)
            .removalListener(listener);
    if (expirationMillis >= 0) {
        b.expireAfterWrite(expirationMillis, TimeUnit.MILLISECONDS);
    }
    return b.build();
}

From source file:com.softinstigate.restheart.handlers.injectors.LocalCachesSingleton.java

private void setup() {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }//w  ww. j ava 2 s  .c  o m

    CacheBuilder builder = CacheBuilder.newBuilder();

    builder.maximumSize(maxCacheSize);

    if (ttl > 0) {
        builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    }

    if (enabled) {
        this.dbPropsCache = builder.build(new CacheLoader<String, Optional<DBObject>>() {
            @Override
            public Optional<DBObject> load(String key) throws Exception {
                return Optional.ofNullable(DBDAO.getDbProps(key));
            }
        });

        this.collectionPropsCache = builder.build(new CacheLoader<String, Optional<DBObject>>() {
            @Override
            public Optional<DBObject> load(String key) throws Exception {
                String[] dbNameAndCollectionName = key.split(SEPARATOR);
                return Optional.ofNullable(CollectionDAO.getCollectionProps(dbNameAndCollectionName[0],
                        dbNameAndCollectionName[1]));
            }
        });
    }
}

From source file:info.magnolia.imaging.caching.CachingImageStreamer.java

public CachingImageStreamer(HierarchyManager hm, CachingStrategy<P> cachingStrategy,
        ImageStreamer<P> delegate) {
    this.hm = hm;
    this.cachingStrategy = cachingStrategy;
    this.delegate = delegate;

    CacheBuilder<Object, Object> cb = CacheBuilder.newBuilder();
    this.currentJobs = cb
            //                    .concurrencyLevel(32)
            //                    .softKeys() weakKeys()
            //                    .softValues() weakValues()

            // entries from the LoadingCache will be removed 500ms after their creation,
            // thus unblocking further requests for an equivalent job.
            .expireAfterWrite(500, TimeUnit.MILLISECONDS)

            .build(new CacheLoader<ImageGenerationJob<P>, NodeData>() {

                @Override//ww w .  j a v a2s  . co m
                public NodeData load(ImageGenerationJob<P> job) throws Exception {
                    try {
                        return generateAndStore(job.getGenerator(), job.getParams());
                    } catch (IOException e) {
                        // the LoadingCache will further wrap these in ExecutionExceptions, and we will, in turn, unwrap them ...
                        throw new RuntimeException(e);
                    } catch (ImagingException e) {
                        // the LoadingCache will further wrap these in ExecutionExceptions, and we will, in turn, unwrap them ...
                        throw new RuntimeException(e);
                    }
                }

            });

}

From source file:com.bazaarvoice.dropwizard.caching.LocalCacheConfiguration.java

public Cache<String, CachedResponse> buildCache() {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();

    if (!_expire.isPresent() && !_maximumSize.isPresent()) {
        cacheBuilder.maximumSize(0);/*from w  w w . j a  v  a2  s .c  o m*/
    } else {
        if (_expire.isPresent()) {
            Duration expire = _expire.get();
            cacheBuilder.expireAfterWrite(expire.getQuantity(), expire.getUnit());
        }

        if (_maximumSize.isPresent()) {
            cacheBuilder.weigher(CachedResponseWeigher.INSTANCE).maximumWeight(_maximumSize.get().toBytes());
        }
    }

    return cacheBuilder.build();
}

From source file:org.alfresco.repo.cache.DefaultSimpleCache.java

/**
 * Construct a cache using the specified capacity and name.
 * /*from w  w w  .  j  av  a  2s . c  om*/
 * @param maxItems The cache capacity. 0 = use {@link #DEFAULT_CAPACITY}
 * @param useMaxItems Whether the maxItems value should be applied as a size-cap for the cache.
 * @param cacheName An arbitrary cache name.
 */
@SuppressWarnings("unchecked")
public DefaultSimpleCache(int maxItems, boolean useMaxItems, int ttlSecs, int maxIdleSecs, String cacheName) {
    if (maxItems == 0) {
        maxItems = DEFAULT_CAPACITY;
    } else if (maxItems < 0) {
        throw new IllegalArgumentException("maxItems may not be negative, but was " + maxItems);
    }
    this.maxItems = maxItems;
    this.useMaxItems = useMaxItems;
    this.ttlSecs = ttlSecs;
    this.maxIdleSecs = maxIdleSecs;
    setBeanName(cacheName);

    // The map will have a bounded size determined by the maxItems member variable.
    @SuppressWarnings("rawtypes")
    CacheBuilder builder = CacheBuilder.newBuilder();

    if (useMaxItems) {
        builder.maximumSize(maxItems);
    }
    if (ttlSecs > 0) {
        builder.expireAfterWrite(ttlSecs, TimeUnit.SECONDS);
    }
    if (maxIdleSecs > 0) {
        builder.expireAfterAccess(maxIdleSecs, TimeUnit.SECONDS);
    }
    builder.concurrencyLevel(32);

    cache = (Cache<K, AbstractMap.SimpleImmutableEntry<K, V>>) builder.build();
}

From source file:com.turbospaces.spaces.SpaceReceiveAdapter.java

@VisibleForTesting
void applyExpireAfterWriteSettings(final CacheBuilder<Object, Object> builder) {
    builder.expireAfterWrite(AbstractSpaceConfiguration.defaultTransactionTimeout(), TimeUnit.SECONDS);
}

From source file:org.hypoport.springGuavaCacheAdapter.SpringGuavaCacheAdapter.java

private void createGuavaCache() {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    if (maximumSize != null) {
        builder.maximumSize(maximumSize);
    }/* ww  w. ja  va 2  s. c o m*/
    if (expireAfterAccessInSeconds != null) {
        builder.expireAfterAccess(expireAfterAccessInSeconds, SECONDS);
    }
    if (expireAfterWriteInSeconds != null) {
        builder.expireAfterWrite(expireAfterWriteInSeconds, SECONDS);
    }
    cache = builder.build();
}

From source file:com.datatorrent.lib.database.CacheStore.java

public CacheStore(CacheProperties properties) {
    Preconditions.checkNotNull(properties.entryExpiryStrategy, "expiryType");

    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    if (properties.entryExpiryStrategy == ExpiryType.EXPIRE_AFTER_ACCESS) {
        cacheBuilder.expireAfterAccess(properties.entryExpiryDurationInMillis, TimeUnit.MILLISECONDS);
    } else if (properties.entryExpiryStrategy == ExpiryType.EXPIRE_AFTER_WRITE) {
        cacheBuilder.expireAfterWrite(properties.entryExpiryDurationInMillis, TimeUnit.MILLISECONDS);
    }//from  w  w  w  .  j  a  v  a 2s.  c om
    cache = cacheBuilder.build();
    this.cleanupScheduler = Executors.newScheduledThreadPool(1);
    cleanupScheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            cache.cleanUp();
        }
    }, properties.cacheCleanupIntervalInMillis, properties.cacheCleanupIntervalInMillis, TimeUnit.MILLISECONDS);
}