Java Code Examples for com.google.common.cache.CacheBuilder#concurrencyLevel()

The following examples show how to use com.google.common.cache.CacheBuilder#concurrencyLevel() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoadingCacheHelper.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
/**
 * 初始化loadingCache
 * @param clazz clazz
 * @param refreshAfterWriteDuration 单位秒
 * @param expireAfterAccessDuration 单位秒
 * @param <K> key
 * @param <V> value
 * @param cacheSize cacheSize
 * @return LoadingCache
 */
private <K, V> LoadingCache<K, V> initLoadingCache(Class<? extends CacheLoader<K, V>> clazz,
		long refreshAfterWriteDuration, long expireAfterAccessDuration, long cacheSize) {
	try {
		log.info("Instantiating LoadingCache: {}", clazz);
		CacheLoader<K, V> cacheLoader = clazz.newInstance();
		CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
		builder.concurrencyLevel(1);
		if (expireAfterAccessDuration > 0) {
			// 在给定时间内没有被读/写访问,则回收
			builder.expireAfterAccess(expireAfterAccessDuration, TimeUnit.SECONDS);
		} else {
			// 自动刷新
			builder.refreshAfterWrite(refreshAfterWriteDuration, TimeUnit.SECONDS);
		}
		if (cacheSize > 0)
			builder.maximumSize(cacheSize);
		LoadingCache<K, V> cache = builder.build(cacheLoader);
		this.loadingCacheMap.put(clazz.getSimpleName(), cache);
		return cache;
	} catch (Exception e) {
		log.error("Error Instantiating LoadingCache: " + clazz, e);
		throw new CommonException(e, "Error Instantiating LoadingCache: " + clazz);
	}
}
 
Example 2
Source File: PerBuildSyscallCache.java    From bazel with Apache License 2.0 6 votes vote down vote up
public PerBuildSyscallCache build() {
  CacheBuilder<Object, Object> statCacheBuilder = CacheBuilder.newBuilder();
  if (maxStats != UNSET) {
    statCacheBuilder = statCacheBuilder.maximumSize(maxStats);
  }
  CacheBuilder<Object, Object> readdirCacheBuilder = CacheBuilder.newBuilder();
  if (maxReaddirs != UNSET) {
    readdirCacheBuilder = readdirCacheBuilder.maximumSize(maxReaddirs);
  }
  if (concurrencyLevel != UNSET) {
    statCacheBuilder = statCacheBuilder.concurrencyLevel(concurrencyLevel);
    readdirCacheBuilder = readdirCacheBuilder.concurrencyLevel(concurrencyLevel);
  }
  return new PerBuildSyscallCache(statCacheBuilder.build(newStatLoader()),
      readdirCacheBuilder.build(newReaddirLoader()));
}
 
Example 3
Source File: VoiceConfig.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public CacheBuilder cacheBuilder() {
   CacheBuilder builder = CacheBuilder.newBuilder();
   if(cacheConcurrencyLevel >= 0) { builder.concurrencyLevel(cacheConcurrencyLevel); }
   if(cacheExpireAfterAccessMs >= 0) { builder.expireAfterAccess(cacheExpireAfterAccessMs, TimeUnit.MILLISECONDS); }
   if(cacheExpireAfterWriteMs >= 0) { builder.expireAfterWrite(cacheExpireAfterWriteMs, TimeUnit.MILLISECONDS); }
   if(cacheInitialCapacity >= 0) { builder.initialCapacity(cacheInitialCapacity); }
   if(cacheMaximumSize >= 0) { builder.maximumSize(cacheMaximumSize); }
   if(cacheRefreshAfterWriteMs >= 0) { builder.refreshAfterWrite(cacheRefreshAfterWriteMs, TimeUnit.MILLISECONDS); }
   if(cacheRecordStats) { builder.recordStats(); }
   return builder;
}
 
Example 4
Source File: DefaultSimpleCache.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Construct a cache using the specified capacity and name.
 * 
 * @param maxItems The cache capacity. 0 = use {@link #DEFAULT_CAPACITY}
 * @param useMaxItems Whether the maxItems value should be applied as a size-cap for the cache.
 * @param cacheName An arbitrary cache name.
 */
@SuppressWarnings("unchecked")
public DefaultSimpleCache(int maxItems, boolean useMaxItems, int ttlSecs, int maxIdleSecs, String cacheName)
{
    if (maxItems == 0)
    {
        maxItems = DEFAULT_CAPACITY;
    }
    else if (maxItems < 0)
    {
        throw new IllegalArgumentException("maxItems may not be negative, but was " + maxItems);
    }
    this.maxItems = maxItems;
    this.useMaxItems = useMaxItems;
    this.ttlSecs = ttlSecs;
    this.maxIdleSecs = maxIdleSecs;
    setBeanName(cacheName);
    
    // The map will have a bounded size determined by the maxItems member variable.
    @SuppressWarnings("rawtypes")
    CacheBuilder builder = CacheBuilder.newBuilder();
    
    if (useMaxItems)
    {
        builder.maximumSize(maxItems);
    }
    if (ttlSecs > 0)
    {
        builder.expireAfterWrite(ttlSecs, TimeUnit.SECONDS);
    }
    if (maxIdleSecs > 0)
    {
        builder.expireAfterAccess(maxIdleSecs, TimeUnit.SECONDS);
    }
    builder.concurrencyLevel(32);
    
    cache = (Cache<K, AbstractMap.SimpleImmutableEntry<K, V>>) builder.build();
}
 
Example 5
Source File: IndicesRequestCache.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private void buildCache() {
    long sizeInBytes = MemorySizeValue.parseBytesSizeValueOrHeapRatio(size, INDICES_CACHE_QUERY_SIZE).bytes();

    CacheBuilder<Key, Value> cacheBuilder = CacheBuilder.newBuilder()
            .maximumWeight(sizeInBytes).weigher(new QueryCacheWeigher()).removalListener(this);
    cacheBuilder.concurrencyLevel(concurrencyLevel);

    if (expire != null) {
        cacheBuilder.expireAfterAccess(expire.millis(), TimeUnit.MILLISECONDS);
    }

    cache = cacheBuilder.build();
}
 
Example 6
Source File: DefaultActiveTraceRepository.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private ConcurrentMap<ActiveTraceHandle, ActiveTrace> createCache(int maxActiveTraceSize) {
    final CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    cacheBuilder.concurrencyLevel(64);
    cacheBuilder.initialCapacity(maxActiveTraceSize);
    cacheBuilder.maximumSize(maxActiveTraceSize);

    final Cache<ActiveTraceHandle, ActiveTrace> localCache = cacheBuilder.build();
    return localCache.asMap();
}
 
Example 7
Source File: SimpleCache.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private ConcurrentMap<T, Result> createCache(int maxCacheSize) {
    final CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    cacheBuilder.concurrencyLevel(64);
    cacheBuilder.initialCapacity(maxCacheSize);
    cacheBuilder.maximumSize(maxCacheSize);
    Cache<T, Result> localCache = cacheBuilder.build();
    ConcurrentMap<T, Result> cache = localCache.asMap();
    return cache;
}
 
Example 8
Source File: LRUCache.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
public LRUCache(int maxCacheSize) {
    final CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    cacheBuilder.concurrencyLevel(32);
    cacheBuilder.initialCapacity(maxCacheSize);
    cacheBuilder.maximumSize(maxCacheSize);
    Cache<T, Object> localCache = cacheBuilder.build();
    this.cache = localCache.asMap();
}
 
Example 9
Source File: GuavaCacheTest.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    CacheBuilder builder = CacheBuilder.newBuilder();
    builder.concurrencyLevel(8);
    builder.maximumSize(1);
    builder.initialCapacity(1);
    Cache<String, Object> cache = builder.build();

    cache.put("test1", "1");
    logger.debug("{}", cache.size());
    cache.put("test3", "2");
    logger.debug("{}", cache.size());

}
 
Example 10
Source File: CachingSubsystemRegistry.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
/**
 * 
 */
@Inject
public CachingSubsystemRegistry(
      SubsystemFactory factory,
      PlaceDAO placeDao,
      ModelDao modelDao,
      PlacePopulationCacheManager populationCacheMgr,
      SubsystemConfig config
) {
   this.factory = factory;
   this.placeDao = placeDao;
   this.modelDao = modelDao;
   this.populationCacheMgr = populationCacheMgr;
   
   CacheBuilder<Object,Object> bld = CacheBuilder.newBuilder();
   if (config.getPlaceCacheConcurrencyLevel() > 0) {
      bld = bld.concurrencyLevel(config.getPlaceCacheConcurrencyLevel());
   }

   if (config.getPlaceCacheExpireAccessMs() > 0) {
      bld =bld.expireAfterAccess(config.getPlaceCacheExpireAccessMs(), TimeUnit.MILLISECONDS);
   }

   if (config.getPlaceCacheInitialCapacity() > 0) {
      bld = bld.initialCapacity(config.getPlaceCacheInitialCapacity());
   }

   if (config.getPlaceCacheMaxSize() > 0) {
      bld = bld.maximumSize(config.getPlaceCacheMaxSize());
   }

   if (config.isPlaceCacheSoftValues()) {
      bld = bld.softValues();
   }

   this.executors = bld
      .recordStats()
      .<UUID, SubsystemExecutor>removalListener((event) -> onRemoved(event.getValue()))
      .build();

   IrisMetricSet metrics = IrisMetrics.metrics("subsystems");
   metrics.monitor("cache", executors);
}
 
Example 11
Source File: IrisSettings.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static CacheBuilder<Object,Object> configurableCacheBuilder(String base, CacheBuilder<Object,Object> builder) {
   // If there is a full cache specification then that overrides everything
   String spec = IrisSettings.getStringProperty(base + ".spec", "");
   if (!spec.isEmpty()) {
      return CacheBuilder.from(spec);
   }

   CacheBuilder<Object,Object> bld = builder;
   int concurrency = IrisSettings.getIntegerProperty(base + ".concurrency", -1);
   if (concurrency > 0) {
      bld = bld.concurrencyLevel(concurrency);
   }

   long write = IrisSettings.getLongProperty(base + ".expire.write", -1L);
   if (write > 0) {
      bld = bld.expireAfterWrite(write, TimeUnit.MILLISECONDS);
   }

   long access = IrisSettings.getLongProperty(base + ".expire.access", -1L);
   if (access > 0) {
      bld = bld.expireAfterAccess(access, TimeUnit.MILLISECONDS);
   }

   long refresh = IrisSettings.getLongProperty(base + ".refresh.write", -1L);
   if (refresh > 0) {
      bld = bld.refreshAfterWrite(refresh, TimeUnit.MILLISECONDS);
   }

   int initsz = IrisSettings.getIntegerProperty(base + ".initial.capacity", -1);
   if (initsz > 0) {
      bld = bld.initialCapacity(initsz);
   }

   int maxsz = IrisSettings.getIntegerProperty(base + ".max.size", -1);
   if (maxsz > 0) {
      bld = bld.maximumSize(maxsz);
   }

   boolean soft = IrisSettings.getBooleanProperty(base + ".soft.values", false);
   if (soft) {
      bld = bld.softValues();
   }

   return bld;
}
 
Example 12
Source File: GuavaUtils.java    From t-io with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param concurrencyLevel
 * @param timeToLiveSeconds 设置写缓存后过期时间(单位:秒)
 * @param timeToIdleSeconds 设置读缓存后过期时间(单位:秒)
 * @param initialCapacity
 * @param maximumSize
 * @param recordStats
 * @param removalListener
 * @return
 */
public static <K, V> LoadingCache<K, V> createLoadingCache(Integer concurrencyLevel, Long timeToLiveSeconds, Long timeToIdleSeconds, Integer initialCapacity,
        Integer maximumSize, boolean recordStats, RemovalListener<K, V> removalListener) {

	if (removalListener == null) {
		removalListener = new RemovalListener<K, V>() {
			@Override
			public void onRemoval(RemovalNotification<K, V> notification) {
				log.info(notification.getKey() + " was removed");
			}
		};
	}

	CacheBuilder<K, V> cacheBuilder = CacheBuilder.newBuilder().removalListener(removalListener);

	//设置并发级别为8,并发级别是指可以同时写缓存的线程数
	cacheBuilder.concurrencyLevel(concurrencyLevel);
	if (timeToLiveSeconds != null && timeToLiveSeconds > 0) {
		//设置写缓存后8秒钟过期
		cacheBuilder.expireAfterWrite(timeToLiveSeconds, TimeUnit.SECONDS);
	}
	if (timeToIdleSeconds != null && timeToIdleSeconds > 0) {
		//设置访问缓存后8秒钟过期
		cacheBuilder.expireAfterAccess(timeToIdleSeconds, TimeUnit.SECONDS);
	}

	//设置缓存容器的初始容量为10
	cacheBuilder.initialCapacity(initialCapacity);
	//设置缓存最大容量为100,超过100之后就会按照LRU最近最少使用算法来移除缓存项
	cacheBuilder.maximumSize(maximumSize);

	if (recordStats) {
		//设置要统计缓存的命中率
		cacheBuilder.recordStats();
	}
	//build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
	LoadingCache<K, V> loadingCache = cacheBuilder.build(new CacheLoader<K, V>() {
		@Override
		public V load(K key) throws Exception {
			return null;
		}
	});
	return loadingCache;

	//		for (int i = 0; i < 20; i++)
	//		{
	//			//从缓存中得到数据,由于我们没有设置过缓存,所以需要通过CacheLoader加载缓存数据
	//			Long student = studentCache.get("p");
	//			System.out.println(student);
	//			//休眠1秒
	//			TimeUnit.SECONDS.sleep(1);
	//		}

	//		System.out.println("cache stats:");
	//最后打印缓存的命中率等 情况
	//		System.out.println(studentCache.stats().toString());
}