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

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

Introduction

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

Prototype

long maximumSize

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

Click Source Link

Usage

From source file:org.socraticgrid.workbench.service.KnowledgeModuleServiceProcessor.java

private KnowledgeModuleServiceProcessor() {
    try {/*from   w w w .  jav  a 2s .  c  o  m*/
        String implName = ApplicationSettings.getInstance().getSetting("knowledge.module.service.impl");
        this.knowledgeModuleService = (KnowledgeModuleService) Class.forName(implName).newInstance();

        useReferenceDataCache = Boolean.parseBoolean(ApplicationSettings.getInstance()
                .getSetting("knowledge.module.service.cache.enabled", "false"));
        if (useReferenceDataCache) {
            String maxCacheSize = ApplicationSettings.getInstance()
                    .getSetting("knowledge.module.service.cache.maxsize");
            String cacheExpirationTime = ApplicationSettings.getInstance()
                    .getSetting("knowledge.module.service.cache.expiration");

            CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();

            if (maxCacheSize != null) {
                cacheBuilder.maximumSize(Long.parseLong(maxCacheSize));
            }
            if (cacheExpirationTime != null) {
                cacheBuilder.expireAfterWrite(Long.parseLong(maxCacheSize), TimeUnit.MINUTES);
            }

            this.referenceDataCache = cacheBuilder.build();
        }

    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}

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

/**
 * Construct a cache using the specified capacity and name.
 * //  www  .  ja va 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:org.geogit.di.caching.CacheFactory.java

protected synchronized void createCache() {
    if (cache != null) {
        return;/*from   www. j  a v a2  s  .c o m*/
    }
    if (!cacheIsEnabled()) {
        this.cache = NO_CACHE;
        return;
    }
    final int maxSize = getConfig("maxSize", 50 * 1000);
    final int concurrencyLevel = getConfig("concurrencyLevel", 0);
    if (concurrencyLevel == 0) {
        this.cache = new SimpleCache<ObjectId, RevObject>(maxSize);
        LOGGER.info("Cache '{}' configured with maxSize: {}", configKeywordPrefix, maxSize);
        return;
    }

    final int expireSeconds = getConfig("expireSeconds", 30);
    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);

    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.trimou.engine.cache.DefaultComputingCacheFactory.java

@Override
public <K, V> ComputingCache<K, V> create(final String consumerId, final Function<K, V> computingFunction,
        final Long expirationTimeout, final Long maxSize, final Listener<K> listener) {

    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();

    if (expirationTimeout != null && expirationTimeout > 0) {
        builder.expireAfterWrite(expirationTimeout, TimeUnit.MILLISECONDS);
    }/*from w  w w . j  a  va2s  .c  om*/
    if (maxSize != null) {
        builder.maximumSize(maxSize);
    }
    if (listener != null) {
        builder.removalListener(new RemovalListener<K, V>() {
            @Override
            public void onRemoval(RemovalNotification<K, V> notification) {
                listener.entryInvalidated(notification.getKey(), notification.getCause().toString());
            }
        });
    }
    return new LoadingCacheAdapter<K, V>(builder.build(new CacheLoaderAdapter<K, V>(computingFunction)));
}

From source file:org.opennms.plugins.elasticsearch.rest.NodeCacheImpl.java

public void init() {
    if (cache == null) {
        LOG.info("initializing node data cache (TTL=" + MAX_TTL + "m, MAX_SIZE=" + MAX_SIZE + ")");
        CacheBuilder cacheBuilder = CacheBuilder.newBuilder();
        if (MAX_TTL > 0) {
            cacheBuilder.expireAfterWrite(MAX_TTL, TimeUnit.MINUTES);
        }/*w w  w .ja v  a  2 s.com*/
        if (MAX_SIZE > 0) {
            cacheBuilder.maximumSize(MAX_SIZE);
        }

        cache = cacheBuilder.build(new CacheLoader<Long, Map<String, String>>() {
            @Override
            public Map<String, String> load(Long key) throws Exception {
                return getNodeAndCategoryInfo(key);
            }
        });
    }
}

From source file:com.navercorp.pinpoint.profiler.context.active.DefaultActiveTraceRepository.java

private ConcurrentMap<ActiveTraceHandle, ActiveTrace> createCache(int maxActiveTraceSize) {
    final CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    cacheBuilder.concurrencyLevel(64);/*from  w w  w  .j a  v  a2  s.  c  o  m*/
    cacheBuilder.initialCapacity(maxActiveTraceSize);
    cacheBuilder.maximumSize(maxActiveTraceSize);

    final Cache<ActiveTraceHandle, ActiveTrace> localCache = cacheBuilder.build();
    return localCache.asMap();
}

From source file:org.elasticsearch.script.ScriptService.java

@Inject
public ScriptService(Settings settings, Environment env, Set<ScriptEngineService> scriptEngines,
        ResourceWatcherService resourceWatcherService) {
    super(settings);

    int cacheMaxSize = componentSettings.getAsInt("cache.max_size", 500);
    TimeValue cacheExpire = componentSettings.getAsTime("cache.expire", null);
    logger.debug("using script cache with max_size [{}], expire [{}]", cacheMaxSize, cacheExpire);

    this.defaultLang = componentSettings.get("default_lang", "mvel");
    this.disableDynamic = componentSettings.getAsBoolean("disable_dynamic", true);

    CacheBuilder cacheBuilder = CacheBuilder.newBuilder();
    if (cacheMaxSize >= 0) {
        cacheBuilder.maximumSize(cacheMaxSize);
    }//from  ww w  . j  a  v  a 2  s .  co  m
    if (cacheExpire != null) {
        cacheBuilder.expireAfterAccess(cacheExpire.nanos(), TimeUnit.NANOSECONDS);
    }
    this.cache = cacheBuilder.build();

    ImmutableMap.Builder<String, ScriptEngineService> builder = ImmutableMap.builder();
    for (ScriptEngineService scriptEngine : scriptEngines) {
        for (String type : scriptEngine.types()) {
            builder.put(type, scriptEngine);
        }
    }
    this.scriptEngines = builder.build();

    // put some default optimized scripts
    staticCache.put("doc.score", new CompiledScript("native", new DocScoreNativeScriptFactory()));

    // add file watcher for static scripts
    scriptsDirectory = new File(env.configFile(), "scripts");
    FileWatcher fileWatcher = new FileWatcher(scriptsDirectory);
    fileWatcher.addListener(new ScriptChangesListener());

    if (componentSettings.getAsBoolean("auto_reload_enabled", true)) {
        // automatic reload is enabled - register scripts
        resourceWatcherService.add(fileWatcher);
    } else {
        // automatic reload is disable just load scripts once
        fileWatcher.init();
    }
}

From source file:org.eclipse.xtext.xbase.ide.types.ClasspathScanner.java

protected Cache<Pair<ClassLoader, Collection<String>>, Iterable<ITypeDescriptor>> createClassLoaderCache() {
    CacheBuilder<Object, Object> _newBuilder = CacheBuilder.newBuilder();
    CacheBuilder<Object, Object> _initialCapacity = _newBuilder.initialCapacity(8);
    CacheBuilder<Object, Object> _concurrencyLevel = _initialCapacity.concurrencyLevel(2);
    CacheBuilder<Object, Object> _maximumSize = _concurrencyLevel.maximumSize(32);
    CacheBuilder<Object, Object> _expireAfterAccess = _maximumSize.expireAfterAccess(5, TimeUnit.MINUTES);
    return _expireAfterAccess.<Pair<ClassLoader, Collection<String>>, Iterable<ITypeDescriptor>>build();
}

From source file:org.eclipse.xtext.xbase.ide.types.ClasspathScanner.java

protected Cache<Pair<URI, Collection<String>>, Iterable<ITypeDescriptor>> createUriCache() {
    CacheBuilder<Object, Object> _newBuilder = CacheBuilder.newBuilder();
    CacheBuilder<Object, Object> _initialCapacity = _newBuilder.initialCapacity(64);
    CacheBuilder<Object, Object> _concurrencyLevel = _initialCapacity.concurrencyLevel(2);
    CacheBuilder<Object, Object> _maximumSize = _concurrencyLevel.maximumSize(256);
    CacheBuilder<Object, Object> _expireAfterAccess = _maximumSize.expireAfterAccess(30, TimeUnit.MINUTES);
    return _expireAfterAccess.<Pair<URI, Collection<String>>, Iterable<ITypeDescriptor>>build();
}

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 ww .  j  av  a 2 s  .  co 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);
                }
            });
}