内存空间是有限的,一些不用的缓存数据需要及时清除,否则容器导致内存溢出。guava最简单一种管理方式是:基于缓存数据个数,让缓存条目始终不能超过一个上限。
// 创建1个cache,最多能存放5个缓存条目
Cache cache = CacheBuilder.newBuilder().recordStats().maximumSize(5).build();
for (int i = 0; i < 10; i++) {
cache.put(i, i);
}
// {6=6, 5=5, 9=9, 7=7, 8=8}
System.out.println(cache.asMap());
guava还提供基于权重的容量管理,相当于是让不同的缓存项占用不同的存储空间。我们的例子中,偶数占用的权重更大,在总权重固定的情况下,缓存能够放下更多的奇数。
// 创建1个cache,最大权重是100,如果缓存值是偶数占20个权重,奇数占5个权重
Cache<Integer, Integer> cache = CacheBuilder.newBuilder().recordStats().
maximumWeight(100).weigher(new Weigher<Integer, Integer>() {
@Override
public int weigh(Integer key, Integer value) {
if (value % 2 == 0) {
return 20;
} else {
return 5;
}
}
}).build();
// 放偶数
f