Joby Wilson Mathews
Joby Wilson Mathews

Reputation: 11136

How to remove expired elements from ehcache without deserialization

I have a background job that removes expired elements from Ehcache by invoking the method ehcache.getQuiet(key). However, the getQuiet(key) method internally deserializes the cached object, which leads to time and memory consumption.

Is there a way to remove expired elements without deserializing the object?

Upvotes: 0

Views: 64

Answers (1)

joana
joana

Reputation: 83

To eliminate expired elements from Ehcache without deserializing them, you can utilize Ehcache's native expiration mechanism and configurations to automatically manage the expired items. If you’re using this way, you avoid the need to manually check and remove each element using methods that deserialize the object's. That is the way to cache listener events

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.event.CacheEventListenerAdapter;

CacheManager manager = CacheManager.getInstance();
Ehcache myCache = manager.getCache("myCache");

myCache.getCacheEventNotificationService().registerListener(new CacheEventListenerAdapter() {
 @Override
 public void notifyElementExpired(Ehcache cacheInstance, Element expiredElement) {
     // Handle expiration, element is already removed from cache
     System.out.println("Expired element: " + expiredElement.getObjectKey());
 }
});

Upvotes: 1

Related Questions