Skip to content

Guava Cache

Calvin Xiao edited this page Nov 15, 2013 · 1 revision

简单缓存用ConcurrentHashMap本来就是传统,而Guava在Map的基础上,又玩出很多花样来,包括

  • 原子的内容加载,当Key在Cache中不存在时,会回调Loader函数,如果有其他并发的对该Key的请求会等待Loader函数而不是重复加载。
  • maximum 数量限制,超出时用LRU(least-recently-used)算法清除。
  • 超时限制,设置max idle time 或 max live time,在每次取元素时都会做超时检查。
  • Key是weak reference, Value是weak 或者 soft reference,真的内存不足时,会被GC掉,慎用。
	LoadingCache<Long, User> cache = CacheBuilder.newBuilder().maximumSize(100)
				.expireAfterAccess(5, TimeUnit.SECONDS).build(new CacheLoader<Long, User>() {
					@Override
					public User load(Long key) throws Exception {
						return accountManager.getUser(key);
					}

				});

在showcase的GuavaCacheDemo中有使用演示。