【发布时间】:2014-03-26 01:03:38
【问题描述】:
我想要:在实体因超时到期而被删除时收到通知。
我试过了:设置移除监听器。
问题: 似乎删除侦听器无法正常工作。仅当我将新项目放入缓存时才有效(请参见下面的代码)
问题: 如何在不添加新项目的情况下使删除侦听器工作?
代码:
我的加载缓存:
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 上分享完整的演示,请告诉我
【问题讨论】:
标签: java collections guava