java - Guava 缓存 : Put operation triggers removal listener

标签 java guava google-guava-cache

我有一个缓存并正在将新元素放入其中。每次我将一个项目放入缓存时,都会触发删除监听器。如何让删除监听器仅在实际被删除或驱逐时才被触发?

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/

相关文章:

java - tomcat 无法获取 ServletContext.getContextPath()

java - 如何根据键对 GSON 数组进行排序?

java - Guava 事件总线 : What does it mean to listen to event supertypes (such as EventObject or Object)?

java - 使用多个分隔符分割查询字符串 - java

java - 如何使用 Guava 将可能的空值转换为默认值?

java - 为什么Guava LoadingCache的getAll方法返回不同类型的ImmutableMap?

java - 如何确定 Guava 缓存中是否存在某个键,以便我不覆盖它?

java - 从文件夹中读取和删除文件

java - Jcombobox - 订阅 selectedItemChanged 事件

java - 实现永久持续的 Guava 缓存