我有一个缓存并正在将新元素放入其中。每次我将一个项目放入缓存时,都会触发删除监听器。如何让删除监听器仅在实际被删除或驱逐时才被触发?
Cache<String, String> cache = CacheBuilder.newBuilder()
// .expireAfterWrite(5, TimeUnit.MINUTES)
.removalListener((RemovalListener<String, String>) notification -> {
System.out.println("Why");
})
.build();
}
cache.put("a","b"); // triggers removal listener
我在这里遗漏了什么吗?为什么不将其称为 PutListener
?
最佳答案
要找到实际原因RemovalNotification.getCause() method应该使用。
要处理除“已替换条目”事件通知之外的所有事件通知,请考虑以下实现草案:
class RemovalListenerImpl implements RemovalListener<String, String> {
@Override
public void onRemoval(final RemovalNotification<String, String> notification) {
if (RemovalCause.REPLACED.equals(notification.getCause())) {
// Ignore the «Entry replaced» event notification.
return;
}
// TODO: Handle the event notification here.
}
}
关于java - Guava 缓存 : Put operation triggers removal listener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45654890/