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:org.jboss.weld.resources.DefaultReflectionCache.java

public DefaultReflectionCache(TypeStore store) {
    this.store = store;
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    this.annotations = cacheBuilder.build(new CacheLoader<AnnotatedElement, Annotations>() {
        @Override// w  w  w.  j  a v a2s.  c  om
        public Annotations load(AnnotatedElement input) {
            return new Annotations(internalGetAnnotations(input));
        }
    });
    this.declaredAnnotations = cacheBuilder.build(new CacheLoader<AnnotatedElement, Annotations>() {
        @Override
        public Annotations load(AnnotatedElement input) {
            return new Annotations(internalGetDeclaredAnnotations(input));
        }
    });
    this.constructorParameterAnnotations = cacheBuilder
            .build(new CacheLoader<Constructor<?>, Annotation[][]>() {
                @Override
                public Annotation[][] load(Constructor<?> input) {
                    return input.getParameterAnnotations();
                }
            });
    this.methodParameterAnnotations = cacheBuilder.build(new CacheLoader<Method, Annotation[][]>() {
        @Override
        public Annotation[][] load(Method input) {
            return input.getParameterAnnotations();
        }
    });
    this.parameterAnnotationSet = cacheBuilder
            .build(new CacheLoader<BackedAnnotatedParameter<?>, Set<Annotation>>() {
                @Override
                public Set<Annotation> load(BackedAnnotatedParameter<?> parameter) throws Exception {
                    final Member member = parameter.getDeclaringCallable().getJavaMember();
                    if (member instanceof Method) {
                        return ImmutableSet
                                .copyOf(getParameterAnnotations((Method) member, parameter.getPosition()));
                    } else {
                        return ImmutableSet.copyOf(
                                getParameterAnnotations((Constructor<?>) member, parameter.getPosition()));
                    }
                }

            });
    this.backedAnnotatedTypeAnnotations = cacheBuilder.build(new BackedAnnotatedTypeAnnotationsFunction());
    this.isScopeAnnotation = cacheBuilder.build(new IsScopeAnnotationFunction());
}

From source file:org.commonjava.aprox.folo.data.FoloRecordCache.java

@PostConstruct
public void buildCache() {
    final CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();

    builder.expireAfterAccess(config.getCacheTimeoutSeconds(), TimeUnit.SECONDS).removalListener(this);

    recordCache = builder.build(this);
}

From source file:name.martingeisse.sql.cache.RowCacheGroup.java

/**
 * Creates a new cache using the specified key expression to fetch missing values, and the
 * valueToKeyMapping to generate keys for the cache.
 * /*from w  ww  .ja v a 2 s .com*/
 * @param keyExpression the key expression
 * @param valueToKeyMapping the mapping that generates keys for the cache
 * @return the cache
 */
public <K> LoadingCache<K, Wrapper<V>> addCache(Expression<?> keyExpression, Function<V, K> valueToKeyMapping) {

    // create the loader
    AbstractDatabaseCacheLoader<K, Wrapper<V>> rowLoader = new RowLoader<K, V>(path, keyExpression,
            additionalPredicates) {
        @Override
        protected Wrapper<V> transformValue(K key, V row) {
            Wrapper<V> wrapper = super.transformValue(key, row);
            if (wrapper.getValue() != null) {
                distributeHelper(wrapper, loaderToCache.get(this), true);
            }
            return wrapper;
        }
    };
    if (database != null) {
        rowLoader = rowLoader.withDatabase(database);
    }

    // create the cache
    @SuppressWarnings("unchecked")
    CacheBuilder<K, Wrapper<V>> typedCacheBuilder = (CacheBuilder<K, Wrapper<V>>) cacheBuilder;
    LoadingCache<K, Wrapper<V>> cache = typedCacheBuilder.build(rowLoader);
    caches.add(cache);
    loaderToCache.put(rowLoader, cache);
    cacheToValueToKeyMapping.put(cache, valueToKeyMapping);
    return cache;

}

From source file:com.streamsets.pipeline.stage.processor.dedup.DeDupProcessor.java

@Override
@SuppressWarnings("unchecked")
protected List<ConfigIssue> init() {
    List<ConfigIssue> issues = super.init();
    if (recordCountWindow <= 0) {
        issues.add(getContext().createConfigIssue(Groups.DE_DUP.name(), "recordCountWindow", Errors.DEDUP_00,
                recordCountWindow));//from w ww  . java  2  s. c om
    }
    if (timeWindowSecs < 0) {
        issues.add(getContext().createConfigIssue(Groups.DE_DUP.name(), "timeWindowSecs", Errors.DEDUP_01,
                timeWindowSecs));
    }
    if (compareFields == SelectFields.SPECIFIED_FIELDS && fieldsToCompare.isEmpty()) {
        issues.add(getContext().createConfigIssue(Groups.DE_DUP.name(), "compareFields", Errors.DEDUP_02));
    }

    long estimatedMemory = MEMORY_USAGE_PER_HASH * recordCountWindow;
    long maxPipelineMemoryBytes = getContext().getPipelineMaxMemory() * 1000 * 1000;
    if (estimatedMemory > maxPipelineMemoryBytes) {
        issues.add(getContext().createConfigIssue(Groups.DE_DUP.name(), "recordCountWindow", Errors.DEDUP_03,
                recordCountWindow, estimatedMemory / (1000 * 1000), getContext().getPipelineMaxMemory()));
        //MiB to bytes conversion, use  1000 * 1000 instead of 1024 * 1024
    }
    if (issues.isEmpty()) {
        hasher = HashingUtil.getHasher("murmur3_128");
        funnel = (compareFields == SelectFields.ALL_FIELDS)
                ? HashingUtil.getRecordFunnel(Collections.EMPTY_LIST)
                : HashingUtil.getRecordFunnel(fieldsToCompare);
        CacheBuilder cacheBuilder = CacheBuilder.newBuilder();
        if (timeWindowSecs > 0) {
            cacheBuilder.expireAfterWrite(timeWindowSecs, TimeUnit.SECONDS);
        }
        hashCache = cacheBuilder.build(new CacheLoader<HashCode, Object>() {
            @Override
            public Object load(HashCode key) throws Exception {
                return VOID;
            }
        });
        hashBuffer = XEvictingQueue.create(recordCountWindow);
        hashAttrName = getInfo() + ".hash";
        uniqueLane = getContext().getOutputLanes().get(OutputStreams.UNIQUE.ordinal());
        duplicateLane = getContext().getOutputLanes().get(OutputStreams.DUPLICATE.ordinal());
    }
    return issues;
}

From source file:com.intelligentsia.dowsers.entity.store.CachedEntityStore.java

/**
 * Build a new instance of <code>CachedEntityStore</code>.
 * /*from w ww .  j  av a 2  s . c o m*/
 * @param entityStore
 * @param cacheBuilder
 */
public CachedEntityStore(final EntityStore entityStore, final CacheBuilder<Object, Object> cacheBuilder) {
    super();
    this.entityStore = Preconditions.checkNotNull(entityStore);
    /**
     * Add specific cache loader.
     */
    entities = cacheBuilder.build(new CacheLoader<KeyCache, Object>() {
        @Override
        public Object load(final KeyCache key) throws Exception {
            return entityStore.find(key.expectedType, key.reference);
        }
    });
}

From source file:org.jboss.weld.metadata.cache.MetaAnnotationStore.java

public MetaAnnotationStore(ClassTransformer classTransformer) {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    this.stereotypes = cacheBuilder.build(new StereotypeFunction(classTransformer));
    this.scopes = cacheBuilder.build(new ScopeFunction(classTransformer));
    this.qualifiers = cacheBuilder.build(new QualifierFunction(classTransformer));
    this.interceptorBindings = cacheBuilder.build(new InterceptorBindingFunction(classTransformer));
    this.qualifierInstanceCache = cacheBuilder.build(new QualifierInstanceFunction(this));
    this.sharedObjectCache = classTransformer.getSharedObjectCache();
}

From source file:rickbw.incubator.cache.TimedEvictionCacheBuilder.java

/**
 * @throws IllegalStateException    If neither {@link #evictAfterAccess()}
 *              nor {@link #evictAfterWrite()} has been called, or if no
 *              periods have been added with
 *              {@link #period(long, TimeUnit, int)}.
 *//*from   ww  w .jav  a 2 s  . c om*/
public LoadingCache<K, V> build(final CacheLoader<? super K, V> loader) {
    if (this.periods.isEmpty()) {
        throw new IllegalStateException("no periods defined");
    } else if (this.periods.size() == 1) {
        final CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
        configureBuilder(builder, this.periods.get(0));
        return builder.build(loader);
    } else {
        assert this.periods.size() > 1;
        final Map<Period, LoadingCache<K, V>> caches = new IdentityHashMap<>();
        for (final Period period : this.periods) {
            final CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
            configureBuilder(builder, period);
            final LoadingCache<K, V> cache = builder.build(loader);
            caches.put(period, cache);
        }
        return new LoadingMultiCache<K, V>(this.elementKeyClass, caches, new PeriodSelector<>(this.periods));
    }
}

From source file:org.jboss.weld.resources.MemberTransformer.java

public MemberTransformer(ClassTransformer transformer) {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    this.transformer = transformer;
    this.unbackedAnnotatedMembersById = cacheBuilder.build(new UnbackedMemberById());
    this.enhancedFieldLoader = new EnhancedFieldLoader();
    this.enhancedMethodLoader = new EnhancedMethodLoader();
    this.enhancedConstructorLoader = new EnhancedConstructorLoader();
    this.enhancedMemberCache = cacheBuilder.build(new EnhancedMemberLoaderFunction());
}

From source file:com.enitalk.configs.DateCache.java

@Bean(name = "exchangeCache")
public LoadingCache<String, BigDecimal> exchange() {
    CacheBuilder<Object, Object> ccc = CacheBuilder.newBuilder();
    ccc.expireAfterWrite(30, TimeUnit.MINUTES);

    LoadingCache<String, BigDecimal> cache = ccc.build(new CacheLoader<String, BigDecimal>() {

        @Override/*from  w  w  w. j a v a  2 s .c o m*/
        public BigDecimal load(String key) throws Exception {
            try {
                return TinkoffController.exchangeRate(jackson);

            } catch (Exception e) {
                logger.error(ExceptionUtils.getFullStackTrace(e));
            }
            return null;
        }

    });

    return cache;
}

From source file:heros.EdgeFunctionCache.java

@SuppressWarnings("unchecked")
public EdgeFunctionCache(final EdgeFunctions<N, D, M, V> delegate,
        @SuppressWarnings("rawtypes") CacheBuilder builder) {
    this.delegate = delegate;

    normalCache = builder.build(new CacheLoader<NDNDKey, EdgeFunction<V>>() {
        public EdgeFunction<V> load(NDNDKey key) throws Exception {
            return delegate.getNormalEdgeFunction(key.getN1(), key.getD1(), key.getN2(), key.getD2());
        }//  ww  w . ja v  a2 s  .  c o  m
    });

    callCache = builder.build(new CacheLoader<CallKey, EdgeFunction<V>>() {
        public EdgeFunction<V> load(CallKey key) throws Exception {
            return delegate.getCallEdgeFunction(key.getCallSite(), key.getD1(), key.getCalleeMethod(),
                    key.getD2());
        }
    });

    returnCache = builder.build(new CacheLoader<ReturnKey, EdgeFunction<V>>() {
        public EdgeFunction<V> load(ReturnKey key) throws Exception {
            return delegate.getReturnEdgeFunction(key.getCallSite(), key.getCalleeMethod(), key.getExitStmt(),
                    key.getD1(), key.getReturnSite(), key.getD2());
        }
    });

    callToReturnCache = builder.build(new CacheLoader<NDNDKey, EdgeFunction<V>>() {
        public EdgeFunction<V> load(NDNDKey key) throws Exception {
            return delegate.getCallToReturnEdgeFunction(key.getN1(), key.getD1(), key.getN2(), key.getD2());
        }
    });
}