Note that there are some explanatory texts on larger screens.

plurals
  1. POGuava CacheBuilder Cache RemovalListener onRemoval doesn't get called everytime though the entry gets removed
    primarykey
    data
    text
    <p>I have created a Guava CacheBuilder based cache with on expiry of 5 seconds if key is not written to. Have added a removalListener to it which prints the key/value pair being removed. What I have observed is that the onRemoval method of the listener gets called only the first time. It doesn't get called the second time an entry is removed. (The actual removal happens. Just the onRemoval method of the removalListener doesn't get called). </p> <p>Am I doing something wrong? Can somebody help? Thanks in advance. Here's my code:</p> <pre><code>import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalListener; import com.google.common.cache.RemovalNotification; public class TestCacheBuilder { public static void main(String[] args) { try { new TestCacheBuilder(); }catch (Exception e){ e.printStackTrace(); } } public TestCacheBuilder() { Cache&lt;String, String&gt; myCache = CacheBuilder.newBuilder() .expireAfterWrite(5, TimeUnit.SECONDS) .removalListener(new RemovalListener&lt;String, String&gt;() { public void onRemoval(RemovalNotification&lt;String, String&gt; removal) { System.out.println("removal: "+removal.getKey()+"/"+removal.getValue()); } }) .build(); Map&lt;String, String&gt; inMap = myCache.asMap(); inMap.put("MyKey", "FirstValue"); System.out.println("Initial Insert: "+inMap); //Wait 16 seconds try { Thread.sleep(4000); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } System.out.println("After 4 seconds: " + inMap); inMap.put("MyKey", "SecondValue"); try { Thread.sleep(1000); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } System.out.println("After 1 more second: " + inMap); try { Thread.sleep(4000); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } System.out.println("After 4 more seconds: " + inMap); } } </code></pre> <p>The output is as below:</p> <pre><code>Initial Insert: {MyKey=FirstValue} After 4 seconds: {MyKey=FirstValue} removal: MyKey/FirstValue After 1 more second: {MyKey=SecondValue} After 4 more seconds: {} </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload