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:org.apache.hedwig.server.topics.AbstractTopicManager.java

public AbstractTopicManager(ServerConfiguration cfg, ScheduledExecutorService scheduler)
        throws UnknownHostException {
    this.cfg = cfg;
    this.queuer = new TopicOpQueuer(scheduler);
    this.scheduler = scheduler;
    addr = cfg.getServerAddr();//from   w  w w  .ja v  a2s  . c  o m

    // build the topic cache
    CacheBuilder<ByteString, TopicStats> cacheBuilder = CacheBuilder.newBuilder()
            .maximumSize(cfg.getMaxNumTopics()).initialCapacity(cfg.getInitNumTopics())
            // TODO: change to same number as topic op queuer threads
            .concurrencyLevel(Runtime.getRuntime().availableProcessors())
            .removalListener(new ReleaseTopicListener());
    if (cfg.getRetentionSecsAfterAccess() > 0) {
        cacheBuilder.expireAfterAccess(cfg.getRetentionSecsAfterAccess(), TimeUnit.SECONDS);
    }
    topics = cacheBuilder.build();
}

From source file:org.nuxeo.ecm.core.storage.dbs.DBSCachingRepository.java

protected <T> Cache<String, T> newCache(DBSRepositoryDescriptor descriptor) {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    builder = builder.expireAfterWrite(descriptor.cacheTTL.longValue(), TimeUnit.MINUTES);
    if (descriptor.cacheConcurrencyLevel != null) {
        builder = builder.concurrencyLevel(descriptor.cacheConcurrencyLevel.intValue());
    }/*from  w  ww .j a  v a 2 s.  c om*/
    if (descriptor.cacheMaxSize != null) {
        builder = builder.maximumSize(descriptor.cacheMaxSize.longValue());
    }
    return builder.build();
}

From source file:org.elasticsearch.indices.cache.request.IndicesRequestCache.java

private void buildCache() {
    long sizeInBytes = MemorySizeValue.parseBytesSizeValueOrHeapRatio(size, INDICES_CACHE_QUERY_SIZE).bytes();

    CacheBuilder<Key, Value> cacheBuilder = CacheBuilder.newBuilder().maximumWeight(sizeInBytes)
            .weigher(new QueryCacheWeigher()).removalListener(this);
    cacheBuilder.concurrencyLevel(concurrencyLevel);

    if (expire != null) {
        cacheBuilder.expireAfterAccess(expire.millis(), TimeUnit.MILLISECONDS);
    }//from  www.j  a v a 2s  .c o m

    cache = cacheBuilder.build();
}

From source file:org.elasticsearch.indices.cache.query.IndicesQueryCache.java

private void buildCache() {
    long sizeInBytes = MemorySizeValue.parseBytesSizeValueOrHeapRatio(size).bytes();

    CacheBuilder<Key, BytesReference> cacheBuilder = CacheBuilder.newBuilder().maximumWeight(sizeInBytes)
            .weigher(new QueryCacheWeigher()).removalListener(this);
    cacheBuilder.concurrencyLevel(concurrencyLevel);

    if (expire != null) {
        cacheBuilder.expireAfterAccess(expire.millis(), TimeUnit.MILLISECONDS);
    }//from   www.  j a va 2s.c  o  m

    cache = cacheBuilder.build();
}

From source file:org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache.java

@Inject
public IndicesFieldDataCache(Settings settings, IndicesFieldDataCacheListener indicesFieldDataCacheListener) {
    super(settings);
    this.indicesFieldDataCacheListener = indicesFieldDataCacheListener;
    String size = componentSettings.get("size", "-1");
    long sizeInBytes = componentSettings.getAsMemory("size", "-1").bytes();
    if (sizeInBytes > ByteSizeValue.MAX_GUAVA_CACHE_SIZE.bytes()) {
        logger.warn("reducing requested field data cache size of [{}] to the maximum allowed size of [{}]",
                new ByteSizeValue(sizeInBytes), ByteSizeValue.MAX_GUAVA_CACHE_SIZE);
        sizeInBytes = ByteSizeValue.MAX_GUAVA_CACHE_SIZE.bytes();
        size = ByteSizeValue.MAX_GUAVA_CACHE_SIZE.toString();
    }/*from   w  w w  .  j ava 2  s .  c  o  m*/
    final TimeValue expire = componentSettings.getAsTime("expire", null);
    CacheBuilder<Key, RamUsage> cacheBuilder = CacheBuilder.newBuilder().removalListener(this);
    if (sizeInBytes > 0) {
        cacheBuilder.maximumWeight(sizeInBytes).weigher(new FieldDataWeigher());
    }
    // defaults to 4, but this is a busy map for all indices, increase it a bit
    cacheBuilder.concurrencyLevel(16);
    if (expire != null && expire.millis() > 0) {
        cacheBuilder.expireAfterAccess(expire.millis(), TimeUnit.MILLISECONDS);
    }
    logger.debug("using size [{}] [{}], expire [{}]", size, new ByteSizeValue(sizeInBytes), expire);
    cache = cacheBuilder.build();
}

From source file:io.datty.unit.UnitSet.java

protected UnitSet(UnitDattyManager parent, String setName, Properties props) {
    this.parent = parent;
    this.name = setName;
    this.props = props;

    String ttlSeconds = props.getProperty(UnitPropertyKeys.MAX_ENTRIES);
    String maxEntries = props.getProperty(UnitPropertyKeys.MAX_ENTRIES);
    if (maxEntries != null) {
        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
        try {//from   www.j a  v  a 2 s. c  o  m
            builder.maximumSize(Integer.parseInt(maxEntries));
        } catch (NumberFormatException e) {
            throw new DattyException(
                    "invalid property maxEntries in set: " + setName + ", value=" + maxEntries);
        }
        if (ttlSeconds != null) {
            try {
                builder.expireAfterWrite(Integer.parseInt(ttlSeconds), TimeUnit.SECONDS);
            } catch (NumberFormatException e) {
                throw new DattyException(
                        "invalid property maxEntries in cache: " + setName + ", value=" + maxEntries);
            }
        }

        this.backingCache = builder.build();
        this.recordMap = backingCache.asMap();
    } else {
        this.backingCache = null;
        this.recordMap = new ConcurrentHashMap<String, UnitRecord>();
    }

}

From source file:org.wso2.andes.store.cache.GuavaBasedMessageCacheImpl.java

public GuavaBasedMessageCacheImpl() {

    DEFAULT_CONTENT_CHUNK_SIZE = AndesConfigurationManager
            .readValue(AndesConfiguration.PERFORMANCE_TUNING_MAX_CONTENT_CHUNK_SIZE);

    long cacheSizeInBytes = 1024L * 1024L
            * ((int) AndesConfigurationManager.readValue(AndesConfiguration.PERSISTENCE_CACHE_SIZE));

    int cacheConcurrency = AndesConfigurationManager
            .readValue(AndesConfiguration.PERSISTENCE_CACHE_CONCURRENCY_LEVEL);

    int cacheExpirySeconds = AndesConfigurationManager
            .readValue(AndesConfiguration.PERSISTENCE_CACHE_EXPIRY_SECONDS);

    String valueRefType = AndesConfigurationManager
            .readValue(AndesConfiguration.PERSISTENCE_CACHE_VALUE_REFERENCE_TYPE);
    printStats = AndesConfigurationManager.readValue(AndesConfiguration.PERSISTENCE_CACHE_PRINT_STATS);

    CacheBuilder<Long, AndesMessage> builder = CacheBuilder.newBuilder().concurrencyLevel(cacheConcurrency)
            .expireAfterAccess(cacheExpirySeconds, TimeUnit.SECONDS).maximumWeight(cacheSizeInBytes)
            .weigher(new Weigher<Long, AndesMessage>() {
                @Override/*from  w  w w  .  j  av  a  2 s  .  com*/
                public int weigh(Long l, AndesMessage m) {
                    return m.getMetadata().getMessageContentLength();
                }
            });

    if (printStats) {
        builder = builder.recordStats();
    }

    if (CACHE_VALUE_REF_TYPE_WEAK.equalsIgnoreCase(valueRefType)) {
        builder = builder.weakValues();
    }

    this.cache = builder.build();

    maintenanceExecutor = Executors.newSingleThreadScheduledExecutor();

    maintenanceExecutor.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            cache.cleanUp();

            if (printStats) {
                log.info("cache stats:" + cache.stats().toString());
            }

        }
    }, 2, 2, TimeUnit.MINUTES);

}

From source file:it.geosolutions.concurrent.ConcurrentTileCache.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();
                }// w w w. j a  va2s.c  o m
            });

    return builder.build();

}

From source file:org.apache.hadoop.hive.llap.AsyncPbRpcProxy.java

public AsyncPbRpcProxy(String name, int numThreads, Configuration conf, Token<TokenType> token,
        long connectionTimeoutMs, long retrySleepMs, int expectedNodes, int maxPerNode) {
    super(name);/*from w  w w  .ja  v  a2  s.  co m*/
    // Note: we may make size/etc. configurable later.
    CacheBuilder<String, ProtocolType> cb = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.HOURS)
            .removalListener(new RemovalListener<String, ProtocolType>() {
                @Override
                public void onRemoval(RemovalNotification<String, ProtocolType> arg) {
                    if (arg == null)
                        return;
                    shutdownProtocolImpl(arg.getValue());
                }
            });
    if (expectedNodes > 0) {
        cb.maximumSize(expectedNodes * 2);
    }
    this.hostProxies = cb.build();
    this.socketFactory = NetUtils.getDefaultSocketFactory(conf);
    this.token = token;
    if (token != null) {
        String tokenUser = getTokenUser(token);
        if (tokenUser == null) {
            try {
                tokenUser = UserGroupInformation.getCurrentUser().getShortUserName();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            LOG.warn("Cannot determine token user from the token; using {}", tokenUser);
        }
        this.tokenUser = tokenUser;
    } else {
        this.tokenUser = null;
    }

    this.retryPolicy = RetryPolicies.retryUpToMaximumTimeWithFixedSleep(connectionTimeoutMs, retrySleepMs,
            TimeUnit.MILLISECONDS);

    this.requestManager = new RequestManager(numThreads, maxPerNode);
    ExecutorService localExecutor = Executors.newFixedThreadPool(1,
            new ThreadFactoryBuilder().setNameFormat("RequestManagerExecutor").build());
    this.requestManagerExecutor = MoreExecutors.listeningDecorator(localExecutor);

    LOG.info("Setting up AsyncPbRpcProxy with" + "numThreads=" + numThreads + "retryTime(millis)="
            + connectionTimeoutMs + "retrySleep(millis)=" + retrySleepMs);
}

From source file:org.graylog2.lookup.caches.GuavaLookupCache.java

@Inject
public GuavaLookupCache(@Assisted("id") String id, @Assisted("name") String name,
        @Assisted LookupCacheConfiguration c, @Named("processbuffer_processors") int processorCount,
        MetricRegistry metricRegistry) {
    super(id, name, c, metricRegistry);
    Config config = (Config) c;//  w ww  .  j a va  2s .  c  o m
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();

    // the theory is that typically only processors will affect the cache concurrency, whereas decorator usage is less critical
    builder.concurrencyLevel(processorCount).recordStats();

    builder.maximumSize(config.maxSize());
    if (config.expireAfterAccess() > 0 && config.expireAfterAccessUnit() != null) {
        //noinspection ConstantConditions
        builder.expireAfterAccess(config.expireAfterAccess(), config.expireAfterAccessUnit());
    }
    if (config.expireAfterWrite() > 0 && config.expireAfterWriteUnit() != null) {
        //noinspection ConstantConditions
        builder.expireAfterWrite(config.expireAfterWrite(), config.expireAfterWriteUnit());
    }

    cache = new InstrumentedCache<>(builder.build(), this);
}