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> LoadingCache<K1, V1> build(CacheLoader<? super K1, V1> loader) 

Source Link

Document

Builds a cache, which either returns an already-loaded value for a given key or atomically computes or retrieves it using the supplied CacheLoader .

Usage

From source file:com.github.benmanes.caffeine.cache.testing.GuavaCacheFromContext.java

/** Returns a Guava-backed cache. */
@SuppressWarnings("CheckReturnValue")
public static <K, V> Cache<K, V> newGuavaCache(CacheContext context) {
    checkState(!context.isAsync(), "Guava caches are synchronous only");

    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    context.guava = builder;/*w  ww  . j  a v a  2 s  .  com*/

    builder.concurrencyLevel(1);
    if (context.initialCapacity != InitialCapacity.DEFAULT) {
        builder.initialCapacity(context.initialCapacity.size());
    }
    if (context.isRecordingStats()) {
        builder.recordStats();
    }
    if (context.maximumSize != Maximum.DISABLED) {
        if (context.weigher == CacheWeigher.DEFAULT) {
            builder.maximumSize(context.maximumSize.max());
        } else {
            builder.weigher(new GuavaWeigher<Object, Object>(context.weigher));
            builder.maximumWeight(context.maximumWeight());
        }
    }
    if (context.afterAccess != Expire.DISABLED) {
        builder.expireAfterAccess(context.afterAccess.timeNanos(), TimeUnit.NANOSECONDS);
    }
    if (context.afterWrite != Expire.DISABLED) {
        builder.expireAfterWrite(context.afterWrite.timeNanos(), TimeUnit.NANOSECONDS);
    }
    if (context.refresh != Expire.DISABLED) {
        builder.refreshAfterWrite(context.refresh.timeNanos(), TimeUnit.NANOSECONDS);
    }
    if (context.expires() || context.refreshes()) {
        builder.ticker(context.ticker());
    }
    if (context.keyStrength == ReferenceType.WEAK) {
        builder.weakKeys();
    } else if (context.keyStrength == ReferenceType.SOFT) {
        throw new IllegalStateException();
    }
    if (context.valueStrength == ReferenceType.WEAK) {
        builder.weakValues();
    } else if (context.valueStrength == ReferenceType.SOFT) {
        builder.softValues();
    }
    if (context.removalListenerType != Listener.DEFAULT) {
        boolean translateZeroExpire = (context.afterAccess == Expire.IMMEDIATELY)
                || (context.afterWrite == Expire.IMMEDIATELY);
        builder.removalListener(new GuavaRemovalListener<>(translateZeroExpire, context.removalListener));
    }
    Ticker ticker = (context.ticker == null) ? Ticker.systemTicker() : context.ticker;
    if (context.loader == null) {
        context.cache = new GuavaCache<>(builder.<Integer, Integer>build(), ticker, context.isRecordingStats());
    } else if (context.loader().isBulk()) {
        context.cache = new GuavaLoadingCache<>(
                builder.build(new BulkLoader<Integer, Integer>(context.loader())), ticker,
                context.isRecordingStats());
    } else {
        context.cache = new GuavaLoadingCache<>(
                builder.build(new SingleLoader<Integer, Integer>(context.loader())), ticker,
                context.isRecordingStats());
    }
    @SuppressWarnings("unchecked")
    Cache<K, V> castedCache = (Cache<K, V>) context.cache;
    return castedCache;
}

From source file:ca.exprofesso.guava.jcache.GuavaCache.java

public GuavaCache(String cacheName, CompleteConfiguration<K, V> configuration, CacheManager cacheManager) {
    this.cacheName = cacheName;
    this.configuration = configuration;
    this.cacheManager = cacheManager;

    String properties = cacheManager.getProperties().toString();

    CacheBuilderSpec cacheBuilderSpec = CacheBuilderSpec
            .parse(properties.substring(1, properties.length() - 1));

    CacheBuilder cacheBuilder = CacheBuilder.from(cacheBuilderSpec);

    ExpiryPolicy expiryPolicy = configuration.getExpiryPolicyFactory().create();

    if (expiryPolicy instanceof ModifiedExpiryPolicy) // == Guava expire after write
    {//from w  w  w .j  a  va 2  s .c o m
        Duration d = expiryPolicy.getExpiryForUpdate();

        cacheBuilder.expireAfterWrite(d.getDurationAmount(), d.getTimeUnit());
    } else if (expiryPolicy instanceof TouchedExpiryPolicy) // == Guava expire after access
    {
        Duration d = expiryPolicy.getExpiryForAccess();

        cacheBuilder.expireAfterAccess(d.getDurationAmount(), d.getTimeUnit());
    }

    this.cacheEntryListenerConfigurations = Sets
            .newHashSet(configuration.getCacheEntryListenerConfigurations());

    if (!this.cacheEntryListenerConfigurations.isEmpty()) {
        cacheBuilder = cacheBuilder.removalListener(this);
    }

    if (configuration.isManagementEnabled()) {
        GuavaCacheMXBean bean = new GuavaCacheMXBean(this);

        try {
            ManagementFactory.getPlatformMBeanServer().registerMBean(bean,
                    new ObjectName(bean.getObjectName()));
        } catch (OperationsException | MBeanException e) {
            throw new CacheException(e);
        }
    }

    if (configuration.isStatisticsEnabled()) {
        GuavaCacheStatisticsMXBean bean = new GuavaCacheStatisticsMXBean(this);

        try {
            ManagementFactory.getPlatformMBeanServer().registerMBean(bean,
                    new ObjectName(bean.getObjectName()));
        } catch (OperationsException | MBeanException e) {
            throw new CacheException(e);
        }

        cacheBuilder.recordStats();
    }

    if (configuration.isReadThrough()) {
        Factory<CacheLoader<K, V>> factory = configuration.getCacheLoaderFactory();

        this.cache = (Cache<K, V>) cacheBuilder.build(new GuavaCacheLoader<>(factory.create()));
    } else {
        this.cache = (Cache<K, V>) cacheBuilder.build();
    }

    this.view = cache.asMap();
}