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

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

Introduction

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

Prototype

long maximumWeight

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

Click Source Link

Usage

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  v  a2  s.  co  m*/
            });

    return builder.build();

}

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   w  ww .j av  a 2 s . c  om*/
            });
    // 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: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   www . java  2  s  .  c  o  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.geowebcache.storage.blobstore.memory.guava.GuavaCacheProvider.java

/**
 * This method is used for creating a new cache object, from the defined configuration.
 * //www .  ja  va  2s .  c o  m
 * @param configuration
 */
private void initCache(CacheConfiguration configuration) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Building new Cache");
    }
    // Initialization step
    int concurrency = configuration.getConcurrencyLevel();
    maxMemory = configuration.getHardMemoryLimit() * BYTES_TO_MB;
    long evictionTime = configuration.getEvictionTime();
    EvictionPolicy policy = configuration.getPolicy();

    // If Cache already exists, flush it
    if (cache != null) {
        cache.invalidateAll();
    }
    // Create the CacheBuilder
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    // Add weigher
    Weigher<String, TileObject> weigher = new Weigher<String, TileObject>() {

        @Override
        public int weigh(String key, TileObject value) {
            currentSize.addAndGet(value.getBlobSize());
            return value.getBlobSize();
        }
    };
    // Create the builder
    CacheBuilder<String, TileObject> newBuilder = builder.maximumWeight(maxMemory).recordStats()
            .weigher(weigher).concurrencyLevel(concurrency)
            .removalListener(new RemovalListener<String, TileObject>() {

                @Override
                public void onRemoval(RemovalNotification<String, TileObject> notification) {
                    // TODO This operation is not atomic
                    TileObject obj = notification.getValue();
                    // Update the current size
                    currentSize.addAndGet(-obj.getBlobSize());
                    final String tileKey = generateTileKey(obj);
                    final String layerName = obj.getLayerName();
                    multimap.removeTile(layerName, tileKey);
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Removed tile " + tileKey + " for layer " + layerName + " due to reason:"
                                + notification.getCause().toString());
                        LOGGER.debug("Removed tile was evicted? " + notification.wasEvicted());
                    }
                }
            });
    // Handle eviction policy
    boolean configuredPolicy = false;
    if (policy != null && evictionTime > 0) {
        if (policy == EvictionPolicy.EXPIRE_AFTER_ACCESS) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Configuring Expire After Access eviction policy");
            }
            newBuilder.expireAfterAccess(evictionTime, TimeUnit.SECONDS);
            configuredPolicy = true;
        } else if (policy == EvictionPolicy.EXPIRE_AFTER_WRITE) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Configuring Expire After Write eviction policy");
            }
            newBuilder.expireAfterWrite(evictionTime, TimeUnit.SECONDS);
            configuredPolicy = true;
        }
    }

    // Build the cache
    cache = newBuilder.build();

    // Created a new multimap
    multimap = new LayerMap();

    // Configure a new scheduling task if needed
    if (configuredPolicy) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Configuring Scheduled Task for cache eviction");
        }
        Runnable command = new Runnable() {

            @Override
            public void run() {
                if (configured.get()) {
                    // Increment the number of current operations
                    // This behavior is used in order to wait
                    // the end of all the operations after setting
                    // the configured parameter to false
                    actualOperations.incrementAndGet();
                    try {
                        cache.cleanUp();
                    } finally {
                        // Decrement the number of current operations.
                        actualOperations.decrementAndGet();
                    }
                }
            }
        };
        // Initialization of the internal Scheduler task for scheduling cache cleanup
        scheduledPool = Executors.newScheduledThreadPool(CORE_POOL_SIZE);
        scheduledPool.scheduleAtFixedRate(command, 10, evictionTime + 1, TimeUnit.SECONDS);
    }

    // Update the configured parameter
    configured.getAndSet(true);
}

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