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

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

Introduction

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

Prototype

public <K1 extends K, V1 extends V> Cache<K1, V1> build() 

Source Link

Document

Builds a cache which does not automatically load values when keys are requested.

Usage

From source file:com.github.pagehelper.cache.GuavaCache.java

public GuavaCache(Properties properties, String prefix) {
    CacheBuilder cacheBuilder = CacheBuilder.newBuilder();
    String maximumSize = properties.getProperty(prefix + ".maximumSize");
    if (StringUtil.isNotEmpty(maximumSize)) {
        cacheBuilder.maximumSize(Long.parseLong(maximumSize));
    } else {//from w ww  . j  av a  2s. c  o  m
        cacheBuilder.maximumSize(1000);
    }
    String expireAfterAccess = properties.getProperty(prefix + ".expireAfterAccess");
    if (StringUtil.isNotEmpty(expireAfterAccess)) {
        cacheBuilder.expireAfterAccess(Long.parseLong(expireAfterAccess), TimeUnit.MILLISECONDS);
    }
    String expireAfterWrite = properties.getProperty(prefix + ".expireAfterWrite");
    if (StringUtil.isNotEmpty(expireAfterWrite)) {
        cacheBuilder.expireAfterWrite(Long.parseLong(expireAfterWrite), TimeUnit.MILLISECONDS);
    }
    String initialCapacity = properties.getProperty(prefix + ".initialCapacity");
    if (StringUtil.isNotEmpty(initialCapacity)) {
        cacheBuilder.initialCapacity(Integer.parseInt(initialCapacity));
    }
    CACHE = cacheBuilder.build();
}

From source file:com.sinotopia.mybatis.pagehelper.cache.GuavaCache.java

public GuavaCache(Properties properties, String prefix) {

    CacheBuilder cacheBuilder = CacheBuilder.newBuilder();
    String maximumSize = properties.getProperty(prefix + ".maximumSize");
    if (StringUtil.isNotEmpty(maximumSize)) {
        cacheBuilder.maximumSize(Long.parseLong(maximumSize));
    } else {// w  ww.  j  av a  2  s.  c  o  m
        cacheBuilder.maximumSize(1000);
    }
    String expireAfterAccess = properties.getProperty(prefix + ".expireAfterAccess");
    if (StringUtil.isNotEmpty(expireAfterAccess)) {
        cacheBuilder.expireAfterAccess(Long.parseLong(expireAfterAccess), TimeUnit.MILLISECONDS);
    }
    String expireAfterWrite = properties.getProperty(prefix + ".expireAfterWrite");
    if (StringUtil.isNotEmpty(expireAfterWrite)) {
        cacheBuilder.expireAfterWrite(Long.parseLong(expireAfterWrite), TimeUnit.MILLISECONDS);
    }
    String initialCapacity = properties.getProperty(prefix + ".initialCapacity");
    if (StringUtil.isNotEmpty(initialCapacity)) {
        cacheBuilder.initialCapacity(Integer.parseInt(initialCapacity));
    }
    CACHE = cacheBuilder.build();
}

From source file:org.apache.hive.hcatalog.common.HiveClientCache.java

/**
 * @param timeout the length of time in seconds after a client is created that it should be automatically removed
 *///from  ww  w  .  j a v a 2s .co  m
private HiveClientCache(final int timeout, final int initialCapacity, final int maxCapacity,
        final boolean enableStats) {
    this.timeout = timeout;
    this.enableStats = enableStats;

    LOG.info("Initializing cache: eviction-timeout=" + timeout + " initial-capacity=" + initialCapacity
            + " maximum-capacity=" + maxCapacity);

    CacheBuilder builder = CacheBuilder.newBuilder().initialCapacity(initialCapacity).maximumSize(maxCapacity)
            .expireAfterAccess(timeout, TimeUnit.SECONDS).removalListener(createRemovalListener());

    /*
     * Guava versions <12.0 have stats collection enabled by default and do not expose a recordStats method.
     * Check for newer versions of the library and ensure that stats collection is enabled by default.
     */
    try {
        java.lang.reflect.Method m = builder.getClass().getMethod("recordStats", null);
        m.invoke(builder, null);
    } catch (NoSuchMethodException e) {
        LOG.debug("Using a version of guava <12.0. Stats collection is enabled by default.");
    } catch (Exception e) {
        LOG.warn("Unable to invoke recordStats method.", e);
    }

    this.hiveCache = builder.build();

    /*
     * We need to use a cleanup interval, which is how often the cleanup thread will kick in
     * and go do a check to see if any of the connections can be expired. We don't want to
     * do this too often, because it'd be like having a mini-GC going off every so often,
     * so we limit it to a minimum of DEFAULT_HIVE_CACHE_EXPIRY_TIME_SECONDS. If the client
     * has explicitly set a larger timeout on the cache, though, we respect that, and use that
     */
    long cleanupInterval = timeout > DEFAULT_HIVE_CACHE_EXPIRY_TIME_SECONDS ? timeout
            : DEFAULT_HIVE_CACHE_EXPIRY_TIME_SECONDS;

    this.cleanupHandle = createCleanupThread(cleanupInterval);

    createShutdownHook();
}

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();
                }//from ww  w. j  ava2  s . com
            });
    // 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: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);
    }//  www.j  a  va  2 s  .  c om
    if (softValues) {
        cacheBuilder.softValues();
    }
    //noinspection unchecked
    return cacheBuilder.build().asMap();
}

From source file:org.apache.ambari.server.security.encryption.InMemoryCredentialStoreService.java

/**
 * Constructs a new InMemoryCredentialStoreService with a specified credential timeout
 *
 * @param retentionDuration the time in some units to keep stored credentials, from the time they are added
 * @param units             the units for the retention duration (minutes, seconds, etc...)
 * @param activelyPurge     true to actively purge credentials after the retention time has expired;
 *                          otherwise false, to passively purge credentials after the retention time has expired
 *///  w  w  w .  j a v a 2  s  .co m
public InMemoryCredentialStoreService(final long retentionDuration, final TimeUnit units,
        boolean activelyPurge) {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();

    // If the retentionDuration is less the 1, then no retention policy is to be enforced
    if (retentionDuration > 0) {
        // If actively purging expired credentials, set up a timer to periodically clean the cache
        if (activelyPurge) {
            ThreadFactory threadFactory = new ThreadFactory() {
                @Override
                public Thread newThread(Runnable runnable) {
                    Thread t = Executors.defaultThreadFactory().newThread(runnable);
                    if (t != null) {
                        t.setName(String.format("%s active cleanup timer",
                                InMemoryCredentialStoreService.class.getSimpleName()));
                        t.setDaemon(true);
                    }
                    return t;
                }
            };
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Cleaning up cache due to retention timeout of {} milliseconds",
                                units.toMillis(retentionDuration));
                    }
                    cache.cleanUp();
                }
            };

            Executors.newSingleThreadScheduledExecutor(threadFactory).schedule(runnable, 1, TimeUnit.MINUTES);
        }

        builder.expireAfterWrite(retentionDuration, units);
    }

    cache = builder.build();
}

From source file:org.opencms.monitor.CmsMemoryMonitor.java

/**
 * Creates a thread safe LRU cache map based on the guava cache builder.<p>
 * Use this instead of synchronized maps for better performance.<p>
 *
 * @param capacity the cache capacity//from   w ww . j a  va2s .  c om
 *
 * @return the cache map
 */
@SuppressWarnings("unchecked")
public static <T, V> Map<T, V> createLRUCacheMap(int capacity) {

    CacheBuilder<?, ?> builder = CacheBuilder.newBuilder().concurrencyLevel(CONCURRENCY_LEVEL)
            .maximumSize(capacity);
    builder.build();
    return (Map<T, V>) (builder.build().asMap());
}

From source file:com.github.benmanes.multiway.TransferPool.java

/** Creates the denormalized cache of resources based on the builder configuration. */
Cache<ResourceKey<K>, R> __makeCache(MultiwayPoolBuilder<? super K, ? super R> builder) {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    if (builder.maximumSize != MultiwayPoolBuilder.UNSET_INT) {
        cacheBuilder.maximumSize(builder.maximumSize);
    }/*from  w w w . ja  v a2  s  .  co  m*/
    if (builder.maximumWeight != MultiwayPoolBuilder.UNSET_INT) {
        cacheBuilder.maximumWeight(builder.maximumWeight);
    }
    if (builder.weigher != null) {
        final Weigher<? super K, ? super R> weigher = builder.weigher;
        cacheBuilder.weigher(new Weigher<ResourceKey<K>, R>() {
            @Override
            public int weigh(ResourceKey<K> resourceKey, R resource) {
                return weigher.weigh(resourceKey.getKey(), resource);
            }
        });
    }
    if (builder.expireAfterWriteNanos != MultiwayPoolBuilder.UNSET_INT) {
        cacheBuilder.expireAfterWrite(builder.expireAfterWriteNanos, TimeUnit.NANOSECONDS);
    }
    if (builder.ticker != null) {
        cacheBuilder.ticker(builder.ticker);
    }
    if (builder.recordStats) {
        cacheBuilder.recordStats();
    }
    cacheBuilder.concurrencyLevel(builder.getConcurrencyLevel());
    cacheBuilder.removalListener(new CacheRemovalListener());
    return cacheBuilder.build();
}

From source file:org.apache.ambari.server.security.encryption.InMemoryCredentialStore.java

/**
 * Constructs a new InMemoryCredentialStore with a specified credential timeout
 *
 * @param retentionDuration the time in some units to keep stored credentials, from the time they are added
 * @param units             the units for the retention duration (minutes, seconds, etc...)
 * @param activelyPurge     true to actively purge credentials after the retention time has expired;
 *                          otherwise false, to passively purge credentials after the retention time has expired
 */// w  w w  .j  av  a2s. c  o  m
public InMemoryCredentialStore(final long retentionDuration, final TimeUnit units, boolean activelyPurge) {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();

    // If the retentionDuration is less the 1, then no retention policy is to be enforced
    if (retentionDuration > 0) {
        // If actively purging expired credentials, set up a timer to periodically clean the cache
        if (activelyPurge) {
            ThreadFactory threadFactory = new ThreadFactory() {
                @Override
                public Thread newThread(Runnable runnable) {
                    Thread t = Executors.defaultThreadFactory().newThread(runnable);
                    if (t != null) {
                        t.setName(String.format("%s active cleanup timer",
                                InMemoryCredentialStore.class.getSimpleName()));
                        t.setDaemon(true);
                    }
                    return t;
                }
            };
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Cleaning up cache due to retention timeout of {} milliseconds",
                                units.toMillis(retentionDuration));
                    }
                    cache.cleanUp();
                }
            };

            Executors.newSingleThreadScheduledExecutor(threadFactory).schedule(runnable, 1, TimeUnit.MINUTES);
        }

        builder.expireAfterWrite(retentionDuration, units);
    }

    cache = builder.build();
}

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

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