2017-08-12 25 views
1

我有一个缓存,并将新元素放入其中。每次我将一个项目放入缓存中时,删除监听器都会被触发。我如何才能让删除监听器仅在事件被移除或驱逐时触发?番石榴高速缓存:放置操作触发器删除监听器

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

+2

你检查notification.getCause()?您是否打印了关键字和移除通知中的值? –

+0

钥匙被更换。我以为我的钥匙是不同的,但他们不是。感谢您的帮助。 – newToScala

回答

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. 
    } 
}