2017-08-12 169 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. 
    } 
}