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

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

Introduction

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

Prototype

public CacheBuilder<K, V> recordStats() 

Source Link

Document

Enable the accumulation of CacheStats during the operation of the cache.

Usage

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//  ww w  .  j a  v  a 2  s .  c om
                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:soot.jimple.infoflow.solver.fastSolver.IFDSSolver.java

/**
 * Creates a solver for the given problem, constructing caches with the
 * given {@link CacheBuilder}. The solver must then be started by calling
 * {@link #solve()}.//from   w w  w  . j a  v a 2 s .  c  o  m
 * @param tabulationProblem The tabulation problem to solve
 * @param flowFunctionCacheBuilder A valid {@link CacheBuilder} or
 * <code>null</code> if no caching is to be used for flow functions.
 */
public IFDSSolver(IFDSTabulationProblem<N, D, M, I> tabulationProblem,
        @SuppressWarnings("rawtypes") CacheBuilder flowFunctionCacheBuilder) {
    if (logger.isDebugEnabled())
        flowFunctionCacheBuilder = flowFunctionCacheBuilder.recordStats();
    this.zeroValue = tabulationProblem.zeroValue();
    this.icfg = tabulationProblem.interproceduralCFG();
    FlowFunctions<N, D, M> flowFunctions = tabulationProblem.autoAddZero()
            ? new ZeroedFlowFunctions<N, D, M>(tabulationProblem.flowFunctions(), zeroValue)
            : tabulationProblem.flowFunctions();
    if (flowFunctionCacheBuilder != null) {
        ffCache = new FlowFunctionCache<N, D, M>(flowFunctions, flowFunctionCacheBuilder);
        flowFunctions = ffCache;
    } else {
        ffCache = null;
    }
    this.flowFunctions = flowFunctions;
    this.initialSeeds = tabulationProblem.initialSeeds();
    this.jumpFn = new JumpFunctions<N, D>();
    this.followReturnsPastSeeds = tabulationProblem.followReturnsPastSeeds();
    this.numThreads = Math.max(1, tabulationProblem.numThreads());
    this.executor = getExecutor();
}

From source file:com.streamsets.pipeline.stage.processor.lookup.ForceLookupProcessor.java

@SuppressWarnings("unchecked")
private Cache<String, Optional<List<Map<String, Field>>>> buildCache() {
    CacheBuilder cacheBuilder = CacheBuilder.newBuilder();

    if (!conf.cacheConfig.enabled) {
        return (conf.lookupMode == QUERY) ? cacheBuilder.maximumSize(0).build(new ForceLookupLoader(this))
                : cacheBuilder.maximumSize(0).build();
    }//from  w  ww. j a va 2 s  .  co  m

    if (conf.cacheConfig.maxSize == -1) {
        conf.cacheConfig.maxSize = Long.MAX_VALUE;
    }

    if (LOG.isDebugEnabled()) {
        cacheBuilder.recordStats();
    }

    // CacheBuilder doesn't support specifying type thus suffers from erasure, so
    // we build it with this if / else logic.
    if (conf.cacheConfig.evictionPolicyType == EvictionPolicyType.EXPIRE_AFTER_ACCESS) {
        cacheBuilder.maximumSize(conf.cacheConfig.maxSize).expireAfterAccess(conf.cacheConfig.expirationTime,
                conf.cacheConfig.timeUnit);
    } else if (conf.cacheConfig.evictionPolicyType == EvictionPolicyType.EXPIRE_AFTER_WRITE) {
        cacheBuilder.maximumSize(conf.cacheConfig.maxSize).expireAfterWrite(conf.cacheConfig.expirationTime,
                conf.cacheConfig.timeUnit);
    } else {
        throw new IllegalArgumentException(
                Utils.format("Unrecognized EvictionPolicyType: '{}'", conf.cacheConfig.evictionPolicyType));
    }

    return (conf.lookupMode == QUERY) ? cacheBuilder.build(new ForceLookupLoader(this)) : cacheBuilder.build();
}

From source file:heros.solver.IDESolver.java

/**
 * Creates a solver for the given problem, constructing caches with the given {@link CacheBuilder}. The solver must then be started by calling
 * {@link #solve()}.//from  w  ww . j ava  2s  .  c  o  m
 * @param flowFunctionCacheBuilder A valid {@link CacheBuilder} or <code>null</code> if no caching is to be used for flow functions.
 * @param edgeFunctionCacheBuilder A valid {@link CacheBuilder} or <code>null</code> if no caching is to be used for edge functions.
 */
public IDESolver(IDETabulationProblem<N, D, M, V, I> tabulationProblem,
        @SuppressWarnings("rawtypes") CacheBuilder flowFunctionCacheBuilder,
        @SuppressWarnings("rawtypes") CacheBuilder edgeFunctionCacheBuilder) {
    if (DEBUG) {
        flowFunctionCacheBuilder = flowFunctionCacheBuilder.recordStats();
        edgeFunctionCacheBuilder = edgeFunctionCacheBuilder.recordStats();
    }
    this.zeroValue = tabulationProblem.zeroValue();
    this.icfg = tabulationProblem.interproceduralCFG();
    FlowFunctions<N, D, M> flowFunctions = new ZeroedFlowFunctions<N, D, M>(tabulationProblem.flowFunctions(),
            tabulationProblem.zeroValue());
    EdgeFunctions<N, D, M, V> edgeFunctions = tabulationProblem.edgeFunctions();
    if (flowFunctionCacheBuilder != null) {
        ffCache = new FlowFunctionCache<N, D, M>(flowFunctions, flowFunctionCacheBuilder);
        flowFunctions = ffCache;
    } else {
        ffCache = null;
    }
    if (edgeFunctionCacheBuilder != null) {
        efCache = new EdgeFunctionCache<N, D, M, V>(edgeFunctions, edgeFunctionCacheBuilder);
        edgeFunctions = efCache;
    } else {
        efCache = null;
    }
    this.flowFunctions = flowFunctions;
    this.edgeFunctions = edgeFunctions;
    this.initialSeeds = tabulationProblem.initialSeeds();
    this.valueLattice = tabulationProblem.joinLattice();
    this.allTop = tabulationProblem.allTopFunction();
    this.jumpFn = new JumpFunctions<N, D, V>(allTop);
}

From source file:org.opennms.netmgt.eventd.AbstractEventUtil.java

public AbstractEventUtil(MetricRegistry registry) {
    // Build the cache, and enable statistics collection if we've been given a metric registry
    final long maximumCacheSize = Long
            .parseLong(System.getProperty("org.opennms.eventd.eventTemplateCacheSize", "1000"));
    final CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder().maximumSize(maximumCacheSize);
    if (registry != null) {
        cacheBuilder.recordStats();
    }/*from  w w  w .j a  v a2  s.  c  o  m*/
    eventTemplateCache = cacheBuilder.build(new CacheLoader<String, EventTemplate>() {
        public EventTemplate load(String key) throws Exception {
            return new EventTemplate(key, AbstractEventUtil.this);
        }
    });

    if (registry != null) {
        // Expose the cache statistics via a series of gauges
        registry.register(MetricRegistry.name("eventutil.cache.capacity"), new Gauge<Long>() {
            @Override
            public Long getValue() {
                return maximumCacheSize;
            }
        });

        registry.register(MetricRegistry.name("eventutil.cache.size"), new Gauge<Long>() {
            @Override
            public Long getValue() {
                return eventTemplateCache.size();
            }
        });

        registry.register(MetricRegistry.name("eventutil.cache.evictioncount"), new Gauge<Long>() {
            @Override
            public Long getValue() {
                return eventTemplateCache.stats().evictionCount();
            }
        });

        registry.register(MetricRegistry.name("eventutil.cache.avgloadpenalty"), new Gauge<Double>() {
            @Override
            public Double getValue() {
                return eventTemplateCache.stats().averageLoadPenalty();
            }
        });
    }
}

From source file:tv.dyndns.kishibe.qmaclone.server.database.CachedDatabase.java

private <K, V> LoadingCache<K, V> build(String name, CacheLoader<K, V> loader) {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder().softValues().expireAfterAccess(1,
            TimeUnit.HOURS);/* ww  w.ja v a2 s  . com*/
    if (ENABLE_CACHE_STATS) {
        builder.recordStats();
    }
    LoadingCache<K, V> cache = builder.build(loader);
    caches.put(name, cache);
    return cache;
}

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  www.  ja v a2  s. c  o m
            });
    // 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:fr.inria.eventcloud.overlay.SemanticCanOverlay.java

/**
 * Constructs a new overlay with the specified datastore instances.
 * /*from  ww  w . ja  va  2  s.c o  m*/
 * @param subscriptionsDatastore
 *            the datastore instance that is used to store subscriptions.
 * 
 * @param miscDatastore
 *            the datastore instance that is used to store miscellaneous
 *            data (publications, historical data, etc.).
 * 
 * @param colanderDatastore
 *            the datastore instance that is used to filter intermediate
 *            results for SPARQL requests from a {@link SparqlColander}.
 */
public SemanticCanOverlay(final TransactionalTdbDatastore subscriptionsDatastore,
        TransactionalTdbDatastore miscDatastore, TransactionalTdbDatastore colanderDatastore) {
    super(new SemanticRequestResponseManager(colanderDatastore));

    this.isBootstrappingPeer = false;

    this.miscDatastore = miscDatastore;
    this.subscriptionsDatastore = subscriptionsDatastore;

    this.miscDatastore.open();
    this.subscriptionsDatastore.open();

    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
            .concurrencyLevel(P2PStructuredProperties.MAO_LIMIT_PEERS.getValue()).softValues()
            .maximumSize(EventCloudProperties.PEER_STUBS_CACHE_MAXIMUM_SIZE.getValue());

    if (EventCloudProperties.RECORD_STATS_PEER_STUBS_CACHE.getValue()) {
        cacheBuilder.recordStats();
    }

    this.peerStubsCache = cacheBuilder.build(new CacheLoader<String, SemanticPeer>() {
        @Override
        public SemanticPeer load(String peerUrl) throws Exception {
            return PAActiveObject.lookupActive(SemanticPeer.class, peerUrl);
        }
    });

    cacheBuilder = CacheBuilder.newBuilder()
            .concurrencyLevel(P2PStructuredProperties.MAO_LIMIT_PEERS.getValue()).softValues()
            .maximumSize(EventCloudProperties.SUBSCRIPTIONS_CACHE_MAXIMUM_SIZE.getValue());

    if (EventCloudProperties.RECORD_STATS_SUBSCRIPTIONS_CACHE.getValue()) {
        cacheBuilder.recordStats();
    }

    this.subscriptionsCache = cacheBuilder.build(new CacheLoader<SubscriptionId, Subscription>() {
        @Override
        public Subscription load(SubscriptionId key) throws SubscriptionNotFoundException {
            Subscription subscription = Subscription.parseFrom(subscriptionsDatastore, key);

            if (subscription == null) {
                throw new SubscriptionNotFoundException(key);
            }

            return subscription;
        }
    });

    this.subscriberConnectionFailures = CacheBuilder.newBuilder().softValues().build();

    if (EventCloudProperties.isSbce2PubSubAlgorithmUsed()
            || EventCloudProperties.isSbce3PubSubAlgorithmUsed()) {
        this.ephemeralSubscriptionsGarbageColletor = Executors.newSingleThreadScheduledExecutor(
                new ThreadFactoryBuilder().setNameFormat("EphemeralSubscriptionsGC").build());
        this.ephemeralSubscriptionsGarbageColletor.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                try {
                    SemanticCanOverlay.this.removeOutdatedEphemeralSubscriptions();
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            }
        }, EventCloudProperties.EPHEMERAL_SUBSCRIPTIONS_GC_TIMEOUT.getValue(),
                EventCloudProperties.EPHEMERAL_SUBSCRIPTIONS_GC_TIMEOUT.getValue(), TimeUnit.MILLISECONDS);
    } else {
        this.ephemeralSubscriptionsGarbageColletor = null;
    }

    this.publishSubscribeOperationsDelayer = new PublishSubscribeDelayer(this);

    if (EventCloudProperties.EXPOSE_JMX_STATISTICS.getValue()) {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

        try {
            mbs.registerMBean(new fr.inria.eventcloud.jmx.SemanticPeerMBeanImpl(this),
                    new ObjectName("fr.inria.eventcloud:type=SemanticPeer,id=" + super.id));
        } catch (InstanceAlreadyExistsException e) {
            e.printStackTrace();
        } catch (MBeanRegistrationException e) {
            e.printStackTrace();
        } catch (NotCompliantMBeanException e) {
            e.printStackTrace();
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        }
    }
}

From source file:uk.q3c.krail.core.user.opt.GuavaCacheConfiguration.java

public CacheBuilder<Object, Object> builder() {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    if (initialCapacity != null) {
        builder.initialCapacity(initialCapacity);
    }//  w w w .j  a  v  a  2  s . c  o m
    if (maximumSize != null) {
        builder.maximumSize(maximumSize);
    }
    if (maximumWeight != null) {
        builder.maximumWeight(maximumWeight);
    }
    if (concurrencyLevel != null) {
        builder.concurrencyLevel(concurrencyLevel);
    }
    if (weakKeys) {
        builder.weakKeys();
    }

    if (weakValues) {
    }
    builder.weakValues();
    if (softValues) {
        builder.softValues();
    }

    if (expireAfterWriteDuration != null) {
        builder.expireAfterWrite(expireAfterWriteDuration, expireAfterWriteTimeUnit);
    }
    if (expireAfterAccessDuration != null) {
        builder.expireAfterAccess(expireAfterAccessDuration, expireAfterAccessTimeUnit);
    }
    if (refreshAfterWriteDuration != null) {
        builder.refreshAfterWrite(refreshAfterWriteDuration, refreshAfterWriteTimeUnit);
    }

    if (ticker != null) {
        builder.ticker(ticker);
    }

    if (removalListener != null) {
        builder.removalListener(removalListener);
    }

    if (recordStats) {
        builder.recordStats();
    }
    return builder;
}

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 ww .j  a  v  a2s.  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();
}