Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If my Ehcache is configured with a TTL, do I need to check if a retrieved Element is expired?

Tags:

java

ehcache

I can't find this anywhere in the Ehcache docs.

Right now I'm using this code to create and configure my Cache:

// Groovy syntax

def cacheConfig = new CacheConfiguration('stats', 1)
cacheConfig.timeToLiveSeconds = 2

def cache = new Cache(cacheConfig)
cache.initialise()

and this to retrieve data:

// Groovy syntax

def cachedElement = cache.get('stats')

if (cachedElement != null && ! cachedElement.isExpired()) {
    // use the cached data
} else {
    // get/generate the data and cache it
}

return cachedElement.value

I wrote this awhile ago, but looking at it now it seems kinda silly to have to check Element.isExpired() — that shouldn't be necessary, right? I mean, if an element is expired, then the cache shouldn't return it — right?

So I'm thinking I can remove that check — just hoping for a quick sanity check here.

Thanks!

like image 366
Avi Flax Avatar asked Sep 15 '25 08:09

Avi Flax


1 Answers

No, you don't have to perform this check. If you get a non-null element back, then it's not expired. It is odd that the javadoc doesn't mention this, right enough, and although I have read this somewhere, I can't find a reference to back up my answer.

like image 145
skaffman Avatar answered Sep 16 '25 23:09

skaffman