List of usage examples for com.google.common.cache CacheBuilder build
public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(CacheLoader<? super K1, V1> loader)
From source file:com.sector91.wit.resources.ResourceLoader.java
public ResourceLoader(ClassLoader context, String rootPath, CacheBuilder<? super String, ? super T> cacheBuilder) { Objects.requireNonNull(context, "A ResourceLoader's ClassLoader cannot be null."); Objects.requireNonNull(rootPath, "A ResourceLoader's root path cannot be null."); this.context = context; while (rootPath.endsWith("/")) rootPath = rootPath.substring(0, rootPath.length() - 1); while (rootPath.startsWith("/")) rootPath = rootPath.substring(1); this.rootPath = rootPath; this.cache = cacheBuilder.build(new ResourceCacheLoader()); Log.trace(TAG, "Created ResourceLoader for path '" + rootPath + "'."); }
From source file:net.voxton.mafiacraft.core.player.PlayerManager.java
/** * Creates the player cache./*from w w w.j a va 2 s. c o m*/ */ private void buildCache() { CacheBuilder builder = CacheBuilder.newBuilder(); builder.maximumSize(10000).expireAfterWrite(10, TimeUnit.MINUTES); builder.removalListener(new RemovalListener<String, MPlayer>() { @Override public void onRemoval(RemovalNotification<String, MPlayer> rn) { savePlayer(rn.getValue()); } }); players = builder.build(new CacheLoader<String, MPlayer>() { @Override public MPlayer load(String key) throws Exception { return loadPlayer(key); } }); }
From source file:org.apache.nifi.minifi.c2.service.ConfigService.java
public ConfigService(List<ConfigurationProvider> configurationProviders, Authorizer authorizer, long maximumCacheSize, long cacheTtlMillis) { this.authorizer = authorizer; this.objectMapper = new ObjectMapper(); if (configurationProviders == null || configurationProviders.size() == 0) { throw new IllegalArgumentException("Expected at least one configuration provider"); }/* w w w. j av a 2 s . c o m*/ this.configurationProviderInfo = Suppliers.memoizeWithExpiration( () -> initContentTypeInfo(configurationProviders), cacheTtlMillis, TimeUnit.MILLISECONDS); CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); if (maximumCacheSize >= 0) { cacheBuilder = cacheBuilder.maximumSize(maximumCacheSize); } if (cacheTtlMillis >= 0) { cacheBuilder = cacheBuilder.refreshAfterWrite(cacheTtlMillis, TimeUnit.MILLISECONDS); } this.configurationCache = cacheBuilder .build(new CacheLoader<ConfigurationProviderKey, ConfigurationProviderValue>() { @Override public ConfigurationProviderValue load(ConfigurationProviderKey key) throws Exception { return initConfigurationProviderValue(key); } }); }
From source file:org.jboss.weld.resources.ClassTransformer.java
public ClassTransformer(TypeStore typeStore, SharedObjectCache cache, ReflectionCache reflectionCache, String contextId) {// w w w. j a va 2 s . c o m this.contextId = contextId; CacheBuilder<Object, Object> defaultBuilder = CacheBuilder.newBuilder(); // if an AnnotatedType reference is not retained by a Bean we are not going to need it at runtime and can therefore drop // it immediately this.backedAnnotatedTypes = CacheBuilder.newBuilder().weakValues() .build(new TransformClassToBackedAnnotatedType()); this.enhancedAnnotatedTypes = defaultBuilder.build(new TransformSlimAnnotatedTypeToEnhancedAnnotatedType()); this.annotations = defaultBuilder.build(new TransformClassToWeldAnnotation()); this.typeStore = typeStore; this.cache = cache; this.reflectionCache = reflectionCache; this.slimAnnotatedTypesById = new ConcurrentHashMap<AnnotatedTypeIdentifier, SlimAnnotatedType<?>>(); }
From source file:io.github.bktlib.command.CommandManagerImpl.java
private void initCaches() { final CacheLoader<String, Optional<CommandBase>> byNameLoader = new CacheLoader<String, Optional<CommandBase>>() { @Override//from ww w. j a v a2s.c om public Optional<CommandBase> load(@Nonnull String key) { org.bukkit.command.Command bukkitCommand = commandMap.getCommand(key); if (!(bukkitCommand instanceof CommandAdapter)) return Optional.empty(); return Optional.of(((CommandAdapter) bukkitCommand).base); } }; final CacheLoader<Class<?>, Optional<CommandBase>> byClassLoader = new CacheLoader<Class<?>, Optional<CommandBase>>() { @Override public Optional<CommandBase> load(@Nonnull Class<?> key) { return commandMap.getCommands().parallelStream().filter(cmd -> cmd.getClass().equals(key)) .filter(cmd -> cmd instanceof CommandAdapter).map(cmd -> ((CommandAdapter) cmd).base) .findAny(); } }; final CacheLoader<Class<?>, Object> classToInstanceLoader = new CacheLoader<Class<?>, Object>() { @Override public Object load(@Nonnull Class<?> aClass) throws Exception { if (aClass == owner.getClass()) { return owner; } if (aClass.getDeclaredConstructors().length != 0) { Constructor<?> constructor = aClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); return constructor.newInstance(); } return aClass.newInstance(); } }; final CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder().weakValues().weakKeys() .maximumSize(1000).expireAfterAccess(5, TimeUnit.MINUTES); byNameCache = cacheBuilder.build(byNameLoader); byClassCache = cacheBuilder.build(byClassLoader); classToInstanceCache = cacheBuilder.build(classToInstanceLoader); }
From source file:com.hazelcast.client.MapClientProxy.java
private LoadingCache buildGuavaCache(NearCacheConfig nc) { CacheBuilder cacheBuilder = CacheBuilder.newBuilder().maximumSize(nc.getMaxSize()); if (nc.getTimeToLiveSeconds() > 0) cacheBuilder.expireAfterWrite(nc.getTimeToLiveSeconds(), TimeUnit.SECONDS); if (nc.getMaxIdleSeconds() > 0) cacheBuilder.expireAfterAccess(nc.getMaxIdleSeconds(), TimeUnit.SECONDS); return cacheBuilder.build(new CacheLoader() { @Override/*from www.j a v a2 s . c om*/ public Object load(Object o) throws Exception { try { return MapClientProxy.this.get0(o); } catch (Exception e) { throw new ExecutionException(e); } } }); }
From source file:org.trimou.engine.cache.DefaultComputingCacheFactory.java
@Override public <K, V> ComputingCache<K, V> create(final String consumerId, final Function<K, V> computingFunction, final Long expirationTimeout, final Long maxSize, final Listener<K> listener) { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); if (expirationTimeout != null && expirationTimeout > 0) { builder.expireAfterWrite(expirationTimeout, TimeUnit.MILLISECONDS); }//from w w w . ja va2 s.c o m if (maxSize != null) { builder.maximumSize(maxSize); } if (listener != null) { builder.removalListener(new RemovalListener<K, V>() { @Override public void onRemoval(RemovalNotification<K, V> notification) { listener.entryInvalidated(notification.getKey(), notification.getCause().toString()); } }); } return new LoadingCacheAdapter<K, V>(builder.build(new CacheLoaderAdapter<K, V>(computingFunction))); }
From source file:net.voxton.mafiacraft.core.city.CityManager.java
/** * Gets the section cache of a world.// ww w . ja v a 2 s . c o m * * @param world The world of the cache. * @return The section cache. */ private Cache<Long, Section> getSectionCache(final MWorld world) { Cache<Long, Section> cache = sections.get(world.getName()); if (cache == null) { CacheBuilder builder = CacheBuilder.newBuilder(); builder.maximumSize(10000).expireAfterWrite(10, TimeUnit.MINUTES); cache = builder.build(new CacheLoader<Long, Section>() { @Override public Section load(Long key) throws Exception { int x = getXFromKey(key); int y = getYFromKey(key); int z = getZFromKey(key); return createSection(world, x, y, z); } }); } sections.put(world.getName(), cache); return cache; }
From source file:com.addthis.hydra.job.store.AvailableCache.java
/** * Make a cache using specified cache parameters * * @param refreshMillis How frequently values should be refreshed in milliseconds (if <= 0, no refresh) * @param expireMillis How old values should have to be before they are expired (if <= 0, they never expire) * @param maxSize How many values should be stored in the cache (if <= 0, no explicit limit) * @param fetchThreads How many threads to use to fetch values in the background (if <=0, use two threads) *///from w w w .ja v a2s . com public AvailableCache(long refreshMillis, long expireMillis, int maxSize, int fetchThreads) { CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); // Configure the cache for any parameters that are > 0 if (expireMillis > 0) { cacheBuilder.expireAfterWrite(expireMillis, TimeUnit.MILLISECONDS); } if (refreshMillis > 0) { cacheBuilder.refreshAfterWrite(refreshMillis, TimeUnit.MILLISECONDS); } if (maxSize > 0) { cacheBuilder.maximumSize(maxSize); } if (fetchThreads <= 0) { fetchThreads = 2; } executor = new ThreadPoolExecutor(fetchThreads, fetchThreads, 1000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new ThreadFactoryBuilder().setNameFormat("avail-cache-%d").setDaemon(true).build()); //noinspection unchecked this.loadingCache = cacheBuilder.build(new CacheLoader<String, Optional<T>>() { @Override /** * If refreshAfterWrite is enabled, this method is called after returning the old value. * The new value will be inserted into the cache when the load() operation completes. */ public ListenableFuture<Optional<T>> reload(final String key, Optional<T> oldValue) { ListenableFutureTask<Optional<T>> task = ListenableFutureTask.create(() -> load(key)); executor.execute(task); return task; } @Override public Optional<T> load(String key) throws Exception { return Optional.fromNullable(fetchValue(key)); } }); }
From source file:com.streamsets.pipeline.lib.jdbc.multithread.JdbcBaseRunnable.java
/** * Builds the Read Context Cache {@link #tableReadContextCache} *///from w w w. j a v a 2 s.c o m @SuppressWarnings("unchecked") private LoadingCache<TableRuntimeContext, TableReadContext> buildReadContextCache( CacheLoader<TableRuntimeContext, TableReadContext> tableCacheLoader) { CacheBuilder resultSetCacheBuilder = CacheBuilder.newBuilder() .removalListener(new JdbcTableReadContextInvalidationListener()); if (tableJdbcConfigBean.batchTableStrategy == BatchTableStrategy.SWITCH_TABLES) { if (tableJdbcConfigBean.resultCacheSize > 0) { resultSetCacheBuilder = resultSetCacheBuilder.maximumSize(tableJdbcConfigBean.resultCacheSize); } } else { resultSetCacheBuilder = resultSetCacheBuilder.maximumSize(1); } if (tableCacheLoader != null) { return resultSetCacheBuilder.build(tableCacheLoader); } else { return resultSetCacheBuilder.build(new JdbcTableReadContextLoader(connectionManager, offsets, tableJdbcConfigBean.fetchSize, tableJdbcConfigBean.quoteChar.getQuoteCharacter(), tableJdbcELEvalContext, isReconnect)); } }