Java 类com.google.common.cache.CacheLoader 实例源码
项目:private-WeChat
文件:AccessTokenJob.java
public AccessTokenJob() {
logger.info("init");
accessTokenCache = CacheBuilder.newBuilder()
// 设置并发级别为200,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(200)
// 设置写缓存后1分钟过期
.expireAfterWrite(90, TimeUnit.MINUTES).initialCapacity(10).maximumSize(100)
// 设置要统计缓存的命中率
.recordStats()
// 设置缓存的移除通知
.removalListener(new RemovalListener<AppIdSecret, String>() {
@Override
public void onRemoval(RemovalNotification<AppIdSecret, String> notification) {
logger.info(notification.getKey() + " was removed, cause by " + notification.getCause());
}
}).build(new CacheLoader<AppIdSecret, String>() {
// build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
@Override
public String load(AppIdSecret appIdSecret) throws Exception {
Token token = CommonUtil.getAccessToken(appIdSecret.getAppId(), appIdSecret.getAppSecret());
return token.getToken();
}
});
}
项目:minebox
文件:MineboxExport.java
private LoadingCache<Integer, Bucket> createFilesCache(final MinebdConfig config) {
Preconditions.checkNotNull(config.parentDirs);
final Integer maxOpenFiles = config.maxOpenFiles;
Preconditions.checkNotNull(maxOpenFiles);
Preconditions.checkArgument(maxOpenFiles > 0);
return CacheBuilder.newBuilder()
.maximumSize(maxOpenFiles)
.removalListener((RemovalListener<Integer, Bucket>) notification -> {
logger.debug("no longer monitoring bucket {}", notification.getKey());
try {
notification.getValue().close();
} catch (IOException e) {
logger.warn("unable to flush and close file " + notification.getKey(), e);
}
})
.build(new CacheLoader<Integer, Bucket>() {
@Override
public Bucket load(Integer key) throws Exception {
return bucketFactory.create(key);
}
});
}
项目:cas-5.1.0
文件:CasEventsInMemoryRepositoryConfiguration.java
@Bean
public CasEventRepository casEventRepository() {
final LoadingCache<String, CasEvent> storage = CacheBuilder.newBuilder()
.initialCapacity(INITIAL_CACHE_SIZE)
.maximumSize(MAX_CACHE_SIZE)
.recordStats()
.expireAfterWrite(EXPIRATION_TIME, TimeUnit.HOURS)
.build(new CacheLoader<String, CasEvent>() {
@Override
public CasEvent load(final String s) throws Exception {
LOGGER.error("Load operation of the cache is not supported.");
return null;
}
});
LOGGER.debug("Created an in-memory event repository to store CAS events for [{}] hours", EXPIRATION_TIME);
return new InMemoryCasEventRepository(storage);
}
项目:cas-5.1.0
文件:MultifactorAuthnTrustConfiguration.java
@ConditionalOnMissingBean(name = "mfaTrustEngine")
@Bean
@RefreshScope
public MultifactorAuthenticationTrustStorage mfaTrustEngine() {
final LoadingCache<String, MultifactorAuthenticationTrustRecord> storage = CacheBuilder.newBuilder()
.initialCapacity(INITIAL_CACHE_SIZE)
.maximumSize(MAX_CACHE_SIZE)
.recordStats()
.expireAfterWrite(casProperties.getAuthn().getMfa().getTrusted().getExpiration(),
casProperties.getAuthn().getMfa().getTrusted().getTimeUnit())
.build(new CacheLoader<String, MultifactorAuthenticationTrustRecord>() {
@Override
public MultifactorAuthenticationTrustRecord load(final String s) throws Exception {
LOGGER.error("Load operation of the cache is not supported.");
return null;
}
});
final InMemoryMultifactorAuthenticationTrustStorage m = new InMemoryMultifactorAuthenticationTrustStorage(storage);
m.setCipherExecutor(mfaTrustCipherExecutor());
return m;
}
项目:cas-5.1.0
文件:OneTimeTokenAuthenticationConfiguration.java
@ConditionalOnMissingBean(name = "oneTimeTokenAuthenticatorTokenRepository")
@Bean
public OneTimeTokenRepository oneTimeTokenAuthenticatorTokenRepository() {
final LoadingCache<String, Collection<OneTimeToken>> storage = CacheBuilder.newBuilder()
.initialCapacity(INITIAL_CACHE_SIZE)
.maximumSize(MAX_CACHE_SIZE)
.recordStats()
.expireAfterWrite(EXPIRE_TOKENS_IN_SECONDS, TimeUnit.SECONDS)
.build(new CacheLoader<String, Collection<OneTimeToken>>() {
@Override
public Collection<OneTimeToken> load(final String s) throws Exception {
LOGGER.error("Load operation of the cache is not supported.");
return null;
}
});
return new CachingOneTimeTokenRepository(storage);
}
项目:hadoop-oss
文件:CachingReEncryptionKeyProvider.java
public CachingReEncryptionKeyProvider(AbstractReEncryptionKeyProvider prov, long keyTimeoutMillis,
long eekTimeoutMillis) {
super(prov.getConf());
this.provider = prov;
reEncryptionKeyCache =
CacheBuilder.newBuilder().expireAfterAccess(keyTimeoutMillis,
TimeUnit.MILLISECONDS)
.build(new CacheLoader<ReEncryptionKeyCacheKey, ReEncryptionKeyInstance>() {
@Override
public ReEncryptionKeyInstance load(ReEncryptionKeyCacheKey key) throws Exception {
ReEncryptionKeyInstance kv = provider.createReEncryptionKey(
key.getSrcKeyName(), key.getDstKeyName());
if (kv == null) {
throw new KeyNotFoundException();
}
return kv;
}
});
transformedEEKCache =
CacheBuilder.newBuilder().expireAfterAccess(eekTimeoutMillis,
TimeUnit.MILLISECONDS)
.build();
}
项目:private-WeChat
文件:AuthorizationController.java
/**
*
*/
public AuthorizationController() {
cache = CacheBuilder.newBuilder()
// 设置并发级别为200,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(200)
// 设置写缓存后1分钟过期
.expireAfterWrite(2, TimeUnit.MINUTES).initialCapacity(10).maximumSize(100)
// 设置要统计缓存的命中率
.recordStats()
// 设置缓存的移除通知
.removalListener(new RemovalListener<String, SNSUserInfo>() {
@Override
public void onRemoval(RemovalNotification<String, SNSUserInfo> notification) {
log.info(notification.getKey() + " was removed, cause by " + notification.getCause());
}
}).build(new CacheLoader<String, SNSUserInfo>() {
// build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
@Override
public SNSUserInfo load(String appIdSecret) throws Exception {
return userInfoCache.get(appIdSecret);
}
});
}
项目:tools
文件:MineboxExport.java
private LoadingCache<Integer, Bucket> createFilesCache(final MinebdConfig config) {
Preconditions.checkNotNull(config.parentDirs);
final Integer maxOpenFiles = config.maxOpenFiles;
Preconditions.checkNotNull(maxOpenFiles);
Preconditions.checkArgument(maxOpenFiles > 0);
return CacheBuilder.newBuilder()
.maximumSize(maxOpenFiles)
.removalListener((RemovalListener<Integer, Bucket>) notification -> {
logger.debug("no longer monitoring bucket {}", notification.getKey());
try {
notification.getValue().close();
} catch (IOException e) {
logger.warn("unable to flush and close file " + notification.getKey(), e);
}
})
.build(new CacheLoader<Integer, Bucket>() {
@Override
public Bucket load(Integer key) throws Exception {
return bucketFactory.create(key);
}
});
}
项目:MantaroRPG
文件:FileCache.java
public FileCache(int maxSize, int concurrencyLevel) {
cache = CacheBuilder.newBuilder()
.maximumSize(maxSize)
.concurrencyLevel(concurrencyLevel)
.build(new CacheLoader<File, byte[]>() {
@SneakyThrows
@Override
public byte[] load(File key) throws Exception {
if (!key.isFile()) throw new IllegalArgumentException(key + ": not a file");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(key);
byte[] buffer = new byte[1024];
int read;
while ((read = fis.read(buffer)) != -1) baos.write(buffer, 0, read);
fis.close();
return baos.toByteArray();
}
});
}
项目:dhus-core
文件:CachedGeocoder.java
/**
* Adds a cache to the given geocoder.
* @param geocoder to decorate.
*/
public CachedGeocoder(Geocoder geocoder)
{
Objects.requireNonNull(geocoder);
decorated = geocoder;
cache = CacheBuilder.newBuilder()
.concurrencyLevel(4)
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.expireAfterAccess(10, TimeUnit.MINUTES)
.build(
new CacheLoader<String, String>()
{
@Override
public String load(String key)
{
return decorated.getBoundariesWKT(key);
}
}
);
}
项目:Equella
文件:MetadataServiceImpl.java
@Override
public Map<String, Map<String, String>> getMetadata(File f)
{
LoadingCache<String, Map<String, String>> metadata = CacheBuilder.newBuilder().build(
CacheLoader.from(new Function<String, Map<String, String>>()
{
@Override
public Map<String, String> apply(String input)
{
return Maps.newHashMap();
}
}));
for( MetadataHandler handler : pluginTracker.getBeanList() )
{
handler.getMetadata(metadata, f);
}
return metadata.asMap();
}
项目:Equella
文件:ConfigurationServiceImpl.java
@SuppressWarnings("unchecked")
private <T> T getFromCache(Object key, String property, final CacheLoader<String, T> loader)
{
Cache<Object, Object> map = cache.getCache();
Object ro = map.getIfPresent(key);
if( ro == null )
{
T newObj = loadFromDb(property, loader);
synchronized( map )
{
map.put(key, newObj != null ? newObj : CACHED_NULL);
return newObj;
}
}
else
{
return ro.equals(CACHED_NULL) ? null : (T) ro;
}
}
项目:sponge
文件:BaseProcessingUnit.java
/**
* Creates a new processing unit.
*
* @param name name.
* @param engine the engine.
* @param inQueue input queue.
* @param outQueue output queue.
*/
public BaseProcessingUnit(String name, Engine engine, EventQueue inQueue, EventQueue outQueue) {
super(name, engine);
this.inQueue = inQueue;
this.outQueue = outQueue;
long cacheExpireTime = engine.getDefaultParameters().getProcessingUnitEventProcessorCacheExpireTime();
if (cacheExpireTime >= 0) {
// Turn on the cache.
CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
if (cacheExpireTime > 0) {
builder.expireAfterAccess(cacheExpireTime, TimeUnit.MILLISECONDS);
}
eventNameProcessorsCache = builder.build(new CacheLoader<String, Set<AtomicReference<T>>>() {
@Override
public Set<AtomicReference<T>> load(String eventName) throws Exception {
return resolveEventProcessors(eventName);
}
});
}
}
项目:sponge
文件:CachedScriptClassInstancePovider.java
public CachedScriptClassInstancePovider(Engine engine, Function<String, S> createScriptFunction, String format,
BiFunction<S, Class<T>, T> createInstanceFunction) {
this.createScriptFunction = createScriptFunction;
this.format = format;
this.createInstanceFunction = createInstanceFunction;
long cacheExpireTime = engine.getDefaultParameters().getScriptClassInstancePoviderCacheExpireTime();
if (cacheExpireTime >= 0) {
// Turn on the cache.
CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
if (cacheExpireTime > 0) {
builder.expireAfterAccess(cacheExpireTime, TimeUnit.MILLISECONDS);
}
cache = builder.build(new CacheLoader<String, S>() {
@Override
public S load(String className) throws Exception {
return createScript(className);
}
});
}
}
项目:Elasticsearch
文件:HunspellService.java
@Inject
public HunspellService(final Settings settings, final Environment env, final Map<String, Dictionary> knownDictionaries) throws IOException {
super(settings);
this.knownDictionaries = knownDictionaries;
this.hunspellDir = resolveHunspellDirectory(settings, env);
this.defaultIgnoreCase = settings.getAsBoolean(HUNSPELL_IGNORE_CASE, false);
dictionaries = CacheBuilder.newBuilder().build(new CacheLoader<String, Dictionary>() {
@Override
public Dictionary load(String locale) throws Exception {
Dictionary dictionary = knownDictionaries.get(locale);
if (dictionary == null) {
dictionary = loadDictionary(locale, settings, env);
}
return dictionary;
}
});
if (!settings.getAsBoolean(HUNSPELL_LAZY_LOAD, false)) {
scanAndLoadDictionaries();
}
}
项目:hadoop
文件:DFSClientCache.java
private CacheLoader<String, DFSClient> clientLoader() {
return new CacheLoader<String, DFSClient>() {
@Override
public DFSClient load(String userName) throws Exception {
UserGroupInformation ugi = getUserGroupInformation(
userName,
UserGroupInformation.getCurrentUser());
// Guava requires CacheLoader never returns null.
return ugi.doAs(new PrivilegedExceptionAction<DFSClient>() {
@Override
public DFSClient run() throws IOException {
return new DFSClient(NameNode.getAddress(config), config);
}
});
}
};
}
项目:athena
文件:AtomixLeaderElector.java
public AtomixLeaderElector(CopycatClient client, Properties properties) {
super(client, properties);
cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.build(CacheLoader.from(topic -> this.client.submit(new GetLeadership(topic))));
cacheUpdater = change -> {
Leadership leadership = change.newValue();
cache.put(leadership.topic(), CompletableFuture.completedFuture(leadership));
};
statusListener = status -> {
if (status == Status.SUSPENDED || status == Status.INACTIVE) {
cache.invalidateAll();
}
};
addStatusChangeListener(statusListener);
}
项目:athena
文件:CachingAsyncConsistentMap.java
/**
* Constructor to configure cache size.
*
* @param backingMap a distributed, strongly consistent map for backing
* @param cacheSize the maximum size of the cache
*/
public CachingAsyncConsistentMap(AsyncConsistentMap<K, V> backingMap, int cacheSize) {
super(backingMap);
cache = CacheBuilder.newBuilder()
.maximumSize(cacheSize)
.build(CacheLoader.from(CachingAsyncConsistentMap.super::get));
cacheUpdater = event -> {
Versioned<V> newValue = event.newValue();
if (newValue == null) {
cache.invalidate(event.key());
} else {
cache.put(event.key(), CompletableFuture.completedFuture(newValue));
}
};
statusListener = status -> {
log.debug("{} status changed to {}", this.name(), status);
// If the status of the underlying map is SUSPENDED or INACTIVE
// we can no longer guarantee that the cache will be in sync.
if (status == SUSPENDED || status == INACTIVE) {
cache.invalidateAll();
}
};
super.addListener(cacheUpdater);
super.addStatusChangeListener(statusListener);
}
项目:modName
文件:GrassColours.java
public static void init() {
ExampleMod.logger.info("ATTEMPTING TO COMMIT GREAT EVIL:");
try {
doImmenseEvil();
} catch(Throwable e) {
e.printStackTrace();
}
MinecraftForge.EVENT_BUS.register(new Listener());
grassCache = CacheBuilder.newBuilder()
.maximumSize(2048)
.build(
new CacheLoader<GrassCacheKey, Biome>() {
@Override
public Biome load(GrassCacheKey key) {
return DimensionManager.getWorld(key.dim).getBiome(new BlockPos(key.x, 63, key.z));
}
}
);
}
项目:Backmemed
文件:SkinManager.java
public SkinManager(TextureManager textureManagerInstance, File skinCacheDirectory, MinecraftSessionService sessionService)
{
this.textureManager = textureManagerInstance;
this.skinCacheDir = skinCacheDirectory;
this.sessionService = sessionService;
this.skinCacheLoader = CacheBuilder.newBuilder().expireAfterAccess(15L, TimeUnit.SECONDS).<GameProfile, Map<Type, MinecraftProfileTexture>>build(new CacheLoader<GameProfile, Map<Type, MinecraftProfileTexture>>()
{
public Map<Type, MinecraftProfileTexture> load(GameProfile p_load_1_) throws Exception
{
try
{
return Minecraft.getMinecraft().getSessionService().getTextures(p_load_1_, false);
}
catch (Throwable var3)
{
return Maps.<Type, MinecraftProfileTexture>newHashMap();
}
}
});
}
项目:waggle-dance
文件:StaticDatabaseMappingService.java
public StaticDatabaseMappingService(
MetaStoreMappingFactory metaStoreMappingFactory,
List<AbstractMetaStore> initialMetastores) {
this.metaStoreMappingFactory = metaStoreMappingFactory;
primaryDatabasesCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).maximumSize(1).build(
new CacheLoader<String, List<String>>() {
@Override
public List<String> load(String key) throws Exception {
if (primaryDatabaseMapping != null) {
return primaryDatabaseMapping.getClient().get_all_databases();
} else {
return Lists.newArrayList();
}
}
});
init(initialMetastores);
}
项目:dremio-oss
文件:JobResultsStore.java
public JobResultsStore(final FileSystemPlugin plugin, final IndexedStore<JobId, JobResult> store,
final BufferAllocator allocator) throws IOException {
this.storageName = plugin.getStorageName();
this.dfs = plugin.getFS(ImpersonationUtil.getProcessUserName());
this.jobStoreLocation = new Path(plugin.getConfig().getPath());
this.dfs.mkdirs(jobStoreLocation);
this.store = store;
this.allocator = allocator;
this.jobResults = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterAccess(15, TimeUnit.MINUTES)
.build(
new CacheLoader<JobId, JobData>() {
@Override
public JobData load(JobId key) throws Exception {
final JobDataImpl jobDataImpl = new JobDataImpl(new LateJobLoader(key), key);
return newJobDataReference(jobDataImpl);
}
});
}
项目:CustomWorldGen
文件:B3DLoader.java
public BakedWrapper(final Node<?> node, final IModelState state, final boolean smooth, final boolean gui3d, final VertexFormat format, final ImmutableSet<String> meshes, final ImmutableMap<String, TextureAtlasSprite> textures)
{
this(node, state, smooth, gui3d, format, meshes, textures, CacheBuilder.newBuilder()
.maximumSize(128)
.expireAfterAccess(2, TimeUnit.MINUTES)
.<Integer, B3DState>build(new CacheLoader<Integer, B3DState>()
{
public B3DState load(Integer frame) throws Exception
{
IModelState parent = state;
Animation newAnimation = node.getAnimation();
if(parent instanceof B3DState)
{
B3DState ps = (B3DState)parent;
parent = ps.getParent();
}
return new B3DState(newAnimation, frame, frame, 0, parent);
}
}));
}
项目:sipsoup
文件:CacheCSSFunction.java
public CacheCSSFunction() {
cache = CacheBuilder.newBuilder().build(new CacheLoader<String, Evaluator>() {
@Override
public Evaluator load(String key) throws Exception {
return QueryParser.parse(key);
}
});
}
项目:Reer
文件:DefaultPluginRegistry.java
private DefaultPluginRegistry(PluginRegistry parent, final PluginInspector pluginInspector, ClassLoaderScope classLoaderScope) {
this.parent = parent;
this.pluginInspector = pluginInspector;
this.classLoaderScope = classLoaderScope;
this.classMappings = CacheBuilder.newBuilder().build(new PotentialPluginCacheLoader(pluginInspector));
this.idMappings = CacheBuilder.newBuilder().build(new CacheLoader<PluginIdLookupCacheKey, Optional<PluginImplementation<?>>>() {
@Override
public Optional<PluginImplementation<?>> load(@SuppressWarnings("NullableProblems") PluginIdLookupCacheKey key) throws Exception {
PluginId pluginId = key.getId();
ClassLoader classLoader = key.getClassLoader();
PluginDescriptorLocator locator = new ClassloaderBackedPluginDescriptorLocator(classLoader);
PluginDescriptor pluginDescriptor = locator.findPluginDescriptor(pluginId.toString());
if (pluginDescriptor == null) {
return Optional.absent();
}
String implClassName = pluginDescriptor.getImplementationClassName();
if (!GUtil.isTrue(implClassName)) {
throw new InvalidPluginException(String.format("No implementation class specified for plugin '%s' in %s.", pluginId, pluginDescriptor));
}
final Class<?> implClass;
try {
implClass = classLoader.loadClass(implClassName);
} catch (ClassNotFoundException e) {
throw new InvalidPluginException(String.format(
"Could not find implementation class '%s' for plugin '%s' specified in %s.", implClassName, pluginId,
pluginDescriptor), e);
}
PotentialPlugin<?> potentialPlugin = pluginInspector.inspect(implClass);
PluginImplementation<Object> withId = new RegistryAwarePluginImplementation(classLoader, pluginId, potentialPlugin);
return Cast.uncheckedCast(Optional.of(withId));
}
});
}
项目:n4js
文件:TestFsmImpl.java
/** Created a new cache loader instance which simply returns with the argument as the loaded value. */
private CacheLoader<String, String> getTestIdCacheLoader() {
return new CacheLoader<String, String>() {
@Override
public String load(final String testId) throws Exception {
return testId;
}
};
}
项目:cas-5.1.0
文件:DefaultDelegatingAuditTrailManager.java
public DefaultDelegatingAuditTrailManager(final AuditTrailManager manager) {
this.manager = manager;
this.storage = CacheBuilder.newBuilder()
.initialCapacity(INITIAL_CACHE_SIZE)
.maximumSize(MAX_CACHE_SIZE)
.recordStats()
.expireAfterWrite(this.expirationDuration, this.expirationTimeUnit)
.build(new CacheLoader<String, AuditActionContext>() {
@Override
public AuditActionContext load(final String s) throws Exception {
LOGGER.error("Load operation of the audit cache is not supported.");
return null;
}
});
}
项目:wakeup-qcloud-sdk
文件:DefaultQCloudClient.java
private void initSigCache() {
this.sigCache = CacheBuilder.newBuilder()
.expireAfterAccess(29, TimeUnit.DAYS)
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) throws Exception {
long expire = 3600 * 24 * 30;// 30天
return getUserSig(key, expire);
}
});
}
项目:helper
文件:CooldownCollection.java
private CooldownCollection(Function<T, String> mappingFunc, Cooldown base) {
this.base = base;
cache = CacheBuilder.newBuilder()
// remove from the cache 10 seconds after the cooldown expires
.expireAfterAccess(base.getTimeout() + 10000L, TimeUnit.MILLISECONDS)
.build(new CacheLoader<String, Cooldown>() {
@Override
public Cooldown load(String s) {
return base.copy();
}
});
this.mappingFunc = mappingFunc;
}
项目:helper
文件:CooldownMapImpl.java
CooldownMapImpl(Cooldown base) {
this.base = base;
this.cache = CacheBuilder.newBuilder()
// remove from the cache 10 seconds after the cooldown expires
.expireAfterAccess(base.getTimeout() + 10000L, TimeUnit.MILLISECONDS)
.build(new CacheLoader<T, Cooldown>() {
@Override
public Cooldown load(@Nonnull T key) {
return base.copy();
}
});
}
项目:helper
文件:ComposedCooldownMapImpl.java
ComposedCooldownMapImpl(Cooldown base, Function<I, O> composeFunction) {
this.base = base;
this.composeFunction = composeFunction;
this.cache = CacheBuilder.newBuilder()
// remove from the cache 10 seconds after the cooldown expires
.expireAfterAccess(base.getTimeout() + 10000L, TimeUnit.MILLISECONDS)
.build(new CacheLoader<O, Cooldown>() {
@Override
public Cooldown load(@Nonnull O key) {
return base.copy();
}
});
}
项目:hadoop-oss
文件:ValueQueue.java
/**
* Constructor takes the following tunable configuration parameters
* @param numValues The number of values cached in the Queue for a
* particular key.
* @param lowWatermark The ratio of (number of current entries/numValues)
* below which the <code>fillQueueForKey()</code> funciton will be
* invoked to fill the Queue.
* @param expiry Expiry time after which the Key and associated Queue are
* evicted from the cache.
* @param numFillerThreads Number of threads to use for the filler thread
* @param policy The SyncGenerationPolicy to use when client
* calls "getAtMost"
* @param refiller implementation of the QueueRefiller
*/
public ValueQueue(final int numValues, final float lowWatermark,
long expiry, int numFillerThreads, SyncGenerationPolicy policy,
final QueueRefiller<E> refiller) {
Preconditions.checkArgument(numValues > 0, "\"numValues\" must be > 0");
Preconditions.checkArgument(((lowWatermark > 0)&&(lowWatermark <= 1)),
"\"lowWatermark\" must be > 0 and <= 1");
Preconditions.checkArgument(expiry > 0, "\"expiry\" must be > 0");
Preconditions.checkArgument(numFillerThreads > 0,
"\"numFillerThreads\" must be > 0");
Preconditions.checkNotNull(policy, "\"policy\" must not be null");
this.refiller = refiller;
this.policy = policy;
this.numValues = numValues;
this.lowWatermark = lowWatermark;
keyQueues = CacheBuilder.newBuilder()
.expireAfterAccess(expiry, TimeUnit.MILLISECONDS)
.build(new CacheLoader<String, LinkedBlockingQueue<E>>() {
@Override
public LinkedBlockingQueue<E> load(String keyName)
throws Exception {
LinkedBlockingQueue<E> keyQueue =
new LinkedBlockingQueue<E>();
refiller.fillQueueForKey(keyName, keyQueue,
(int)(lowWatermark * numValues));
return keyQueue;
}
});
executor =
new ThreadPoolExecutor(numFillerThreads, numFillerThreads, 0L,
TimeUnit.MILLISECONDS, queue, new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(REFILL_THREAD).build());
}
项目:hadoop-oss
文件:CodecPool.java
private static <T> LoadingCache<Class<T>, AtomicInteger> createCache(
Class<T> klass) {
return CacheBuilder.newBuilder().build(
new CacheLoader<Class<T>, AtomicInteger>() {
@Override
public AtomicInteger load(Class<T> key) throws Exception {
return new AtomicInteger();
}
});
}
项目:tac-kbp-eal
文件:CorpusQueryExecutor2016.java
/**
* The default query matching strategy for the 2016 evaluation.
*/
public static EREBasedCorpusQueryExecutor createDefaultFor2016(
final Map<Symbol, File> docIdToEREMap,
final ERELoader ereLoader, final EREToKBPEventOntologyMapper ontologyMapper,
int slack, double minNominalCASOverlap,
boolean requireBestCASType) {
final LoadingCache<Symbol, EREDocument> ereDocCache = CacheBuilder.newBuilder()
.maximumSize(50)
.build(new CacheLoader<Symbol, EREDocument>() {
@Override
public EREDocument load(final Symbol docID) throws Exception {
final File ereFileName = docIdToEREMap.get(docID);
if (ereFileName != null) {
return ereLoader.loadFrom(ereFileName);
} else {
throw new TACKBPEALException("Cannot find ERE file for " + docID);
}
}
});
final ResponsePJContainsEntryPJWithSlack commonPJMatchStrategy =
new ResponsePJContainsEntryPJWithSlack(slack);
final ImmutableList<AlignmentConfiguration> alignmentConfigs = ImmutableList.of(
AlignmentConfiguration.of(ExactCASMatch.INSTANCE, commonPJMatchStrategy),
AlignmentConfiguration.of(QueryNameContainsSystemCAS.INSTANCE, commonPJMatchStrategy),
AlignmentConfiguration.of(QueryNameContainedBySystemCAS.INSTANCE, commonPJMatchStrategy),
AlignmentConfiguration.of(
new NominalsContainOneAnotherWithMinimumOverlap(minNominalCASOverlap),
commonPJMatchStrategy));
return new EREBasedCorpusQueryExecutor(alignmentConfigs, ereDocCache, ontologyMapper,
requireBestCASType);
}
项目:tac-kbp-eal
文件:AssessmentSpecFormats.java
private DirectoryAnnotationStore(final File directory, AssessmentCreator assessmentCreator,
final boolean doCaching, final Format format) throws IOException {
checkArgument(directory.exists(), "Directory %s for annotation store does not exist",
directory);
// this is a half-hearted attempt at preventing multiple assessment stores
// being opened on the same directory at once. There is a race condition,
// but we don't anticipate this class being used concurrently enough to justify
// dealing with it.
lockFile = new File(directory, "__lock");
if (lockFile.exists()) {
throw new IOException(String.format(
"Directory %s for assessment store is locked; if this is due to a crash, delete %s",
directory, lockFile));
}
this.directory = checkNotNull(directory);
this.cache = CacheBuilder.newBuilder().maximumSize(50)
.build(new CacheLoader<Symbol, AnswerKey>() {
@Override
public AnswerKey load(Symbol key) throws Exception {
return DirectoryAnnotationStore.this.uncachedRead(key);
}
});
this.docIDs = loadInitialDocIds();
this.assessmentCreator = checkNotNull(assessmentCreator);
this.doCaching = doCaching;
this.format = checkNotNull(format);
}
项目:private-WeChat
文件:TicketJob.java
public TicketJob() {
logger.info("init");
ticketCache = CacheBuilder.newBuilder()
// 设置并发级别为200,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(200)
// 设置写缓存后1分钟过期
.expireAfterWrite(90, TimeUnit.MINUTES).initialCapacity(10)
.maximumSize(100)
// 设置要统计缓存的命中率
.recordStats()
// 设置缓存的移除通知
.removalListener(new RemovalListener<AppIdSecret, String>() {
@Override
public void onRemoval(
RemovalNotification<AppIdSecret, String> notification) {
logger.info(notification.getKey()
+ " was removed, cause by "
+ notification.getCause());
}
}).build(new CacheLoader<AppIdSecret, String>() {
// build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
@Override
public String load(AppIdSecret appIdSecret)
throws Exception {
String accessToken = accessTokenJob.getAccessToken(appIdSecret);
JsapiTicket ticket = CommonUtil.getJsapiTicket(accessToken);
return ticket.getTicket();
}
});
}
项目:private-WeChat
文件:LoadingCacheTest.java
/**
* @param args
* @throws ExecutionException
* @throws InterruptedException
*/
public static void main(String[] args) throws ExecutionException, InterruptedException {
LoadingCache<String, String> cache = null;
cache = CacheBuilder.newBuilder()
// 设置并发级别为200,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(200)
// 设置写缓存后1分钟过期
.expireAfterWrite(1, TimeUnit.SECONDS).initialCapacity(10).maximumSize(100)
// 设置要统计缓存的命中率
.recordStats()
// 设置缓存的移除通知
.removalListener(new RemovalListener<String, String>() {
@Override
public void onRemoval(RemovalNotification<String, String> notification) {
System.out.println(notification.getKey() + " was removed, cause by " + notification.getCause());
}
}).build(new CacheLoader<String, String>() {
// build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
@Override
public String load(String appIdSecret) throws Exception {
return "";
}
});
cache.put("key1", "value1");
System.out.println(cache.get("key1"));
Thread.sleep(2000);
System.out.println(cache.get("key1"));
}
项目:drift
文件:SslContextFactory.java
private SslContextFactory()
{
this.cache = CacheBuilder.newBuilder()
.expireAfterAccess(1, TimeUnit.HOURS)
.build(CacheLoader.from(key ->
new ReloadableSslContext(
key.getTrustCertificatesFile(),
key.getClientCertificatesFile(),
key.getPrivateKeyFile(),
key.getPrivateKeyPassword(),
key.getSessionCacheSize(),
key.getSessionTimeout(),
key.getCiphers())));
}
项目:drift
文件:ConnectionPool.java
public ConnectionPool(ConnectionManager connectionFactory, EventLoopGroup group, DriftNettyClientConfig config)
{
this.connectionFactory = connectionFactory;
this.group = requireNonNull(group, "group is null");
requireNonNull(config, "config is null");
// todo from config
cachedConnections = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterAccess(10, TimeUnit.MINUTES)
.<HostAndPort, Future<Channel>>removalListener(notification -> closeConnection(notification.getValue()))
.build(new CacheLoader<HostAndPort, Future<Channel>>()
{
@Override
public Future<Channel> load(HostAndPort address)
throws Exception
{
return createConnection(address);
}
});
maintenanceThread = newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
.setNameFormat("drift-connection-maintenance-%s")
.setDaemon(true)
.build());
maintenanceThread.scheduleWithFixedDelay(cachedConnections::cleanUp, 1, 1, TimeUnit.SECONDS);
}
项目:crawling-framework
文件:EsHttpSourcesCache.java
private static synchronized LoadingCache<String, HttpSource> getInstance(
final EsHttpSourceOperations operations) {
if (INSTANCE == null) {
INSTANCE = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(new CacheLoader<String, HttpSource>() {
public HttpSource load(String url) {
return operations.get(url);
}
});
}
return INSTANCE;
}