Listening to Cache Entry Expired events

Whenever a Cache entry is expired, an event (i.e., CacheEntryEvent) is generated.

In this post under JCache, I will show with an example how to create a listener to listen for those events and respond.

We have to create a listener class which implements the javax.cache.event.CacheEntryExpiredListener interface as shown below


import java.util.Iterator;

import javax.cache.event.CacheEntryEvent;
import javax.cache.event.CacheEntryExpiredListener;
import javax.cache.event.CacheEntryListenerException;

public class CacheEntryExpiredListenerImpl implements CacheEntryExpiredListener {
    @Override
    public void onExpired(Iterable<CacheEntryEvent> iterable)
            throws CacheEntryListenerException {
        Iterator<CacheEntryEvent> iterator = iterable.iterator();
        for(;iterator.hasNext();) {
            CacheEntryEvent cacheEntryEvent = iterator.next();
            System.out.println("Entry removed: " + cacheEntryEvent.getKey() + "-->" + cacheEntryEvent.getValue());
        }
    }
}

In the above code, we have created a class named “CacheEntryExpiredListenerImpl” that implements the interface “CacheEntryExpiredListener” and provides implementation for the interface method “onExpired”. This method is called whenever a cache entry is expired and the cache detects that. It receives a list of CacheEntryEvent as an parameter, whose details we are printing in the for loop.

Next I will show how to register the listener to the cache.

Main Code


1  import java.util.Iterator;
2  
3  import javax.cache.Cache;
4  import javax.cache.Cache.Entry;
5  import javax.cache.CacheManager;
6  import javax.cache.Caching;
7  import javax.cache.configuration.Factory;
8  import javax.cache.configuration.FactoryBuilder;
9  import javax.cache.configuration.MutableCacheEntryListenerConfiguration;
10 import javax.cache.configuration.MutableConfiguration;
11 import javax.cache.expiry.CreatedExpiryPolicy;
12 import javax.cache.expiry.Duration;
13 import javax.cache.expiry.ExpiryPolicy;
14 import javax.cache.spi.CachingProvider;
15 
16 public class JCacheDemo12 {
17  public static void main(String[] args) throws InterruptedException {
18      CachingProvider cachingProvider = Caching.getCachingProvider();
19      CacheManager cacheManager = cachingProvider.getCacheManager();
20      
21      Factory expiryPolicyFactory = CreatedExpiryPolicy.factoryOf(Duration.ONE_MINUTE);
22      
23      MutableConfiguration mutableConfiguration = new MutableConfiguration();
24      mutableConfiguration.setTypes(String.class, String.class);
25      mutableConfiguration.setExpiryPolicyFactory(expiryPolicyFactory);
26      
27      MutableCacheEntryListenerConfiguration mutableCacheEntryListenerConfiguration = new MutableCacheEntryListenerConfiguration(FactoryBuilder.factoryOf(CacheEntryExpiredListenerImpl.class), null, true, true);
28      
29      Cache cache = cacheManager.createCache("cache1", mutableConfiguration);
30      cache.registerCacheEntryListener(mutableCacheEntryListenerConfiguration);
31      cache.put("key1", "value1");
32      cache.put("key2", "value2");
33      cache.put("key3", "value3");
34      cache.put("key4", "value4");
35      
36      Thread.sleep(120000);
37      
38      Iterator<Entry> iterator = cache.iterator();
39      while(iterator.hasNext()) {
40          Entry entry = iterator.next();
41          if(entry != null)
42              System.out.println(entry.getKey() + ":" + entry.getValue());
43      }
44      
45      cache.deregisterCacheEntryListener(mutableCacheEntryListenerConfiguration);
46      
47      cachingProvider.close();
48  }
49 }

In the above code, at line 27, we create an instance of MutableCacheEntryListenerConfiguration. It takes the following as arguments
1) Factory instance to create instances of CacheEntryExpiredListenerImpl
2) Factory instance to create instance of CacheEntryEventFilter implementation
3) a boolean value indicating whether old value is required or not
4) a boolean value indicating whether the listenerFactory should block the thread causing the event or not

At line 30, we register the instance of MutableCacheEntryListenerConfiguration with the cache by calling registerCacheEntryListener method.

From now on whenever a entry is expired from the cache and when cache detects that, our custom listener will be called.

At line 45, we deregister the instance of MutableCacheEntryListenerConfiguration from the cache by calling deregisterCacheEntryListener method.

Output

SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Entry removed: key2–>value2
Entry removed: key1–>value1
Entry removed: key4–>value4
Entry removed: key3–>value3

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s