【发布时间】:2014-07-24 21:25:35
【问题描述】:
我打算在我的应用程序中使用 Guava Cache。一些被访问的 [K, V] 对在统计上 >> 比其他的对,应该基本上总是在缓存中可用。
根据Sized Based Eviction的规范
如果您的缓存不应超过一定大小,只需使用 CacheBuilder.maximumSize(long)。缓存将尝试驱逐条目 最近或不经常使用的东西
我试图理解非常经常部分。我可以假设 - 对于maximumSize = 100 的缓存,如果Key_A 被访问10000 次并立即发布有100 put 调用,Key_A 仍将存在于缓存中?我进行的基本单元测试似乎无法证实这一事实。 有什么想法吗?
public class CacheHelper
{
private Cache<String, String> cache;
public CacheHelper()
{
cache = CacheBuilder.newBuilder().maximumSize(10).concurrencyLevel(1).build();
}
public String fetchVal(String key)
{
String val = cache.getIfPresent(key);
return val;
}
public void putVal(String key, String val)
{
cache.put(key, val);
}
}
测试
public class CacheTest
{
public static void main(String[] args)
{
CacheHelper cacheHelper = new CacheHelper();
cacheHelper.putVal("0", "0");
for(int i = 0; i < 10000; i++)
{
cacheHelper.fetchVal("0");
}
System.out.println(cacheHelper.fetchVal("0"));
for(int i = 1; i < 11; i++)
{
String key = "" + i;
cacheHelper.putVal(key, key);
}
System.out.println(cacheHelper.fetchVal("0")); // Still returns NULL - "most often not being used?"
}
}
谢谢
【问题讨论】: