Search code examples
javahibernatecachingehcache

ehcache based on date


I'm working with ehcache 2.5.4.

I have an object that needs to be cached through out the day and refreshed with a new value at 00:00am every day.

Currently with ehcache configurations I can only set the time to live and time to idle, but that will depend on the time I created the object or when it's used. ie:

    <cache
    name="cache.expiry.application.date_status"
    maxElementsInMemory="10"
    eternal="false"
    timeToIdleSeconds="60"
    timeToLiveSeconds="50" />

Is there a way to get ehcache to expire specific caches based on specific times.


Solution

  • I've done this by extending Ehcache's Element class like so:

    class EvictOnGivenTimestampElement extends Element {
    
        private static final long serialVersionUID = ...;
        private final long evictOn;
    
        EvictOnGivenTimestampElement(final Serializable key, final Serializable value, final long evictOn) {
            super(key, value);
            this.evictOn = evictOn;
        }
    
        @Override
        public boolean isExpired() {
            return System.currentTimeMillis() > evictOn;
        }
    }
    

    The rest is as easy as putting new instance of EvictOnGivenTimestampElement object into the cache instead of Element.

    Advantage of this approach is that you don't have to worry about external cronjobs, etc. And the obvious disadvantage is the attachment to Ehcache API which I hope won't change too often.