gpt4 book ai didi

java - Guava CacheBuilder 不调用移除监听器

转载 作者:搜寻专家 更新时间:2023-10-30 21:06:55 24 4
gpt4 key购买 nike

我想要:当实体因超时到期而被移除时收到通知。

我尝试过: 设置删除监听器。

问题: 删除监听器似乎无法正常工作。它仅在我将新项目放入缓存时起作用(请参见下面的代码)

问题: 如何在不放置新项目的情况下使删除监听器工作?

代码:

我的加载缓存:

LoadingCache<String, Integer> ints = CacheBuilder.newBuilder()
.maximumSize(10000)
.expireAfterAccess(ACCESS_TIMEOUT, TimeUnit.MILLISECONDS)
.removalListener(
new RemovalListener() {
//PROBLEM: THIS METHOD IS NEVER CALLED!!!
public void onRemoval(RemovalNotification notification) {
if (notification.getCause() == RemovalCause.EXPIRED) {
System.out.println("Value " + notification.getValue() + " has been expired");
} else {
System.out.println("Just removed for some reason");
}
}
}
)
.build(
new CacheLoader<String, Integer>() {
public Integer load(String key) throws Exception {
return new Integer(-1);
}
});

我如何在单独的线程中使用缓存:

cache.put("key", 100);
Thread.sleep(ACCESS_TIMEOUT / 2);
System.out.println(cache.getIfPresent(key)); //returns 100
Thread.sleep(ACCESS_TIMEOUT * 5);
//CRUCIAL STRING: cache.put("key2", 200); //invoke removal listener
System.out.println(cache.getIfPresent(key)); //return null
//And again: the problem is that entity has been already expired, but removal listener isn't called untill I add new item to the cache.

P.S:如果你需要,我可以在 GitHub 上分享完整的演示,告诉我

最佳答案

这是因为 Guava 无法确保在超时值到期时自动驱逐这些值。然而,它会在一系列读写操作期间执行此操作。

根据其文档 here :

Caches built with CacheBuilder do not perform cleanup and evict values "automatically," or instantly after a value expires, or anything of the sort. Instead, it performs small amounts of maintenance during write operations, or during occasional read operations if writes are rare.

The reason for this is as follows: if we wanted to perform Cache maintenance continuously, we would need to create a thread, and its operations would be competing with user operations for shared locks. Additionally, some environments restrict the creation of threads, which would make CacheBuilder unusable in that environment.

要在到期时验证您的onRemoval,请调用cache#cleanUp就在您的第二次读取操作之前,它应该调用您的 onRemoval

关于java - Guava CacheBuilder 不调用移除监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21986551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com