【问题标题】:Guava 18.0 refreshAfterWriteGuava 18.0 refreshAfterWrite
【发布时间】:2015-06-17 14:47:56
【问题描述】:

番石榴 18.0.

我正在尝试解决 refreshAfterWrite

我认为使用以下代码

 return the **key on load** 
 after 3 seconds
 return update the key to uppercase (automatically)

这是加载器

 ExecutorService executor = Executors.newCachedThreadPool();
    mockLoader = new CacheLoader<String, String>() {
        //return key
        @Override
        public String load(String key) throws Exception {
            System.out.println("loaindg.....");
            return key;
        }
        // load-behind. asyn loading.
        @Override
        public ListenableFuture<String> reload(final String key, String result) {
            ListenableFutureTask<String> task = ListenableFutureTask.create(new Callable<String>() {
                public String call() {
                    System.out.println("reloaindg.....");
                    return key.toUpperCase();
                }
            });
            executor.execute(task);
            return task;
        }
    };
}

这是缓存

cache.setRefreshAfterWrite(3);
cache.setCacehLoader(mockLoader);

但在测试中,重新加载没有按预期发生。

String key = "a";
String firstGet = cache.get(key);
assertTrue(key.equals(firstGet));
sleep(refrehTime + 3);
// I must use the get to trigger the reload
String secondGet = cache.get(key);
assertTrue(key.toUpperCase().equals(secondGet));

这是正确的吗?

可以自动触发重载吗?

【问题讨论】:

    标签: java guava


    【解决方案1】:

    这是由于在执行程序上异步执行刷新,这允许读取是非阻塞的并返回陈旧的值。如果您使用MoreExecutors.directExecutor(),则测试将通过。另请注意,您可以使用FakeTicker 来操纵时间而不是睡眠。或者,您可能更喜欢使用过期而不是刷新。

    过期和刷新是密切相关但不同的机制。过期的条目被认为是陈旧的并且不能被使用,所以它必须被丢弃并重新获取。符合刷新条件的条目意味着内容仍然可以使用,但应该重新获取数据,因为它可能已过期。 Guava 提供了这些 TTL 策略,名为 expireAfterWrite 和 refreshAfterWrite,如果刷新时间小于过期时间,可以一起使用。

    回复scalacache memoization asynchronous refresh

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 2012-04-20
      • 2013-09-17
      相关资源
      最近更新 更多