首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Cache2K自动refreshAhead无法按预期工作

Cache2K自动refreshAhead无法按预期工作
EN

Stack Overflow用户
提问于 2021-03-31 23:19:55
回答 1查看 96关注 0票数 0

我正在尝试使用org.cache2k库创建具有自动刷新元素的缓存。例如,我定义了持续时间为5秒的元素加载器。我将过期时间设置为5秒。并且我将keepDataAfterExpired和refreshAhead选项设置为true。

第一次调用get方法大约持续5秒。没问题的。然后,我预计元素将过期,并在接下来的15秒内自动重新加载,第二个get将不会延迟地获取元素。但我的输出是:

结果

5011

结果

5000

第二个get和第一个一样持续5秒。我的目标是让元素自动刷新,并且只有第一个get会延迟。它是否可达,以及如何实现?谢谢。

代码语言:javascript
复制
    static String expensiveOperation(String name) throws InterruptedException {
        Thread.sleep(5000);
        return "result";
    }

    public static void main (String... args) throws InterruptedException {
        Cache<String,String> cache = new Cache2kBuilder<String, String>() {}
                .expireAfterWrite(5000, TimeUnit.MILLISECONDS)    // expire/refresh after 5 seconds
                .keepDataAfterExpired(true)
                .refreshAhead(true)                       // keep fresh when expiring
                .loader(s->expensiveOperation(s))         // auto populating function
                .build();

        Instant i1 = Instant.now();
        System.out.println(cache.get("a"));
        Instant i2 = Instant.now();
        System.out.println(Duration.between(i1,i2).toMillis());

        Thread.sleep(15000);

        Instant i11 = Instant.now();
        System.out.println(cache.get("a"));
        Instant i22 = Instant.now();
        System.out.println(Duration.between(i11,i22).toMillis());
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-07 12:16:10

我在Cache2k中关于refreshAhead的文档中找到了答案:

刷新后,条目将处于试用期。如果在下一次到期之前无法访问该条目,则不会进行刷新,该条目将过期并将从缓存中删除。这意味着条目在试用期内停留的时间由配置的过期时间或ExpiryPolicy确定。

因此,在我的示例中,15秒足以让条目自动刷新,然后过期并删除,因此下一个get触发新的加载。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66890633

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档