I am trying to get only valid objects from the cache. if I do List list = cache.getKeys();, it will also return keys that have expired. I want to add a listener and try to remove the key myself, but my listener is notifyElementExpirednever called.
Here is my code:
public static void main(String[] args) throws Exception {
CacheManager.getInstance().addCache("test");
Cache cache = CacheManager.getInstance().getCache("test");
cache.getCacheConfiguration().setTimeToLiveSeconds(10);
cache.getCacheEventNotificationService().registerListener(new CacheEventListener() {
public void notifyRemoveAll(Ehcache arg0) {
System.out.println("notifyRemoveAll cache=" + arg0);
}
public void notifyElementUpdated(Ehcache arg0, Element arg1)
throws CacheException {
System.out.println("notifyElementUpdated cache=" + arg0 + " element=" + arg1);
}
public void notifyElementRemoved(Ehcache arg0, Element arg1)
throws CacheException {
System.out.println("notifyElementRemoved cache=" + arg0 + " element=" + arg1);
}
public void notifyElementPut(Ehcache arg0, Element arg1)
throws CacheException {
System.out.println("notifyElementPut cache=" + arg0 + " element=" + arg1);
}
public void notifyElementExpired(Ehcache arg0, Element arg1) {
System.out.println("notifyElementExpired cache=" + arg0 + " element=" + arg1);
}
public void notifyElementEvicted(Ehcache arg0, Element arg1) {
System.out.println("notifyElementEvicted cache=" + arg0 + " element=" + arg1);
}
public void dispose() {
System.out.println("dispose");
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
});
String key = "key";
String value = "value1";
System.out.println("created at = " + new Date());
cache.put(new Element(key, value, false, new Integer(1), new Integer(5)));
System.out.println("key=" + key + "will expired at object=" + new Date(cache.get(key).getExpirationTime()));
Thread.sleep(7000);
@SuppressWarnings("unchecked")
List list = cache.getKeys();
System.out.println("current time = " + new Date());
for (Object item : list) {
System.out.println("created at = " + new Date());
}
Thread.sleep(30000);
}
source
share