VB_*_*VB_ 13 java collections guava
我想:在超时到期时删除实体时收到通知.
我试过:设置删除监听器.
问题: 似乎删除侦听器无法正常工作.它只在我将新项目放入缓存时才有效(参见下面的代码)
问题: 如何在不放置新项目的情况下使删除侦听器工作?
码:
我的加载缓存:
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);
}
});
Run Code Online (Sandbox Code Playgroud)
我如何在单独的线程中使用缓存:
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.
Run Code Online (Sandbox Code Playgroud)
PS:如果需要,我可以在GitHub上分享完整的演示,告诉我
Pop*_*ibo 15
这是因为当超时值到期时,Guava无法确保自动驱逐值.然而,它在一系列读写操作期间执行此操作.
每它的文档在这里:
使用CacheBuilder构建的缓存不会"自动"执行清理和逐出值,或者在值到期后立即执行或逐出任何类型.相反,它在写入操作期间执行少量维护,或者在写入很少的情况下偶尔执行读取操作.
原因如下:如果我们想要连续执行缓存维护,我们需要创建一个线程,其操作将与共享锁的用户操作竞争.此外,某些环境会限制线程的创建,这会使CacheBuilder在该环境中无法使用.
要验证您onRemoval的到期日期,请cache#cleanUp在第二次阅读操作之前立即致电,并且应该拨打您的电话onRemoval.
| 归档时间: |
|
| 查看次数: |
3925 次 |
| 最近记录: |