【问题标题】:Guava Cache - maximumSize - Eviction (LRU or most often)Guava Cache - maximumSize - Eviction (LRU or most often)
【发布时间】: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?"
    }
}

谢谢

【问题讨论】:

    标签: caching guava


    【解决方案1】:

    根据我的理解,Guava Cache 使用 LRU 作为默认驱逐策略

    在您的情况下,当您添加 10 个新值时,键“0”的条目成为最旧的值,因此最旧的值在缓存达到其最大大小时被驱逐。

    【讨论】:

      【解决方案2】:

      问题是番石榴规范说“经常或最近”,在您的情况下,1 到 10 键比 0 键更近。 这就是 0 键消失的原因。

      如果性能对您很重要,请尝试使用缓存加载器。多亏了加载器,guava 可以确定加载值的延迟,并将大多数“有用”的项目保存在内存中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-19
        • 2020-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多