番石榴缓存:放置操作触发器删除侦听器

时间:2017-08-12 20:59:24

标签: 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

1 个答案:

答案 0 :(得分:1)

要查找实际原因,请使用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.
    }
}