我有一个缓存,正在将新元素放入其中。每次我将项目放入缓存时,都会触发删除监听器。如何仅在实际删除或收回事物时才触发删除监听器?
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.
}
}