kaqqao
kaqqao

Reputation: 15459

Eagerly repopulate EhCache instead of waiting for a read

In my scenario, getting the fresh (non-cached) values is a very expensive operation so it is imperative pre-calculated cached values exist at all times instead of refreshing them on read, like EhCache seems to do.

For this it sounds reasonable to have a thread firing on TTL expiration repopulating the cache with fresh values, so no reads are ever waiting.

Is there a way to achieve this using Ehcache? Listening for OnElementExpired/Evicted events to repopulate the cache seems like a no-go (by the time I receive the event, a read would already be waiting).

I guess I could make the cache itself eternal and have my own scheduled task that repopulates, but then I get nothing from EhCache over dumb maps that I have now. Is this really how it is? Is there no way to have EhCache help me in this situation?

Upvotes: 0

Views: 1038

Answers (3)

Louis Jacomet
Louis Jacomet

Reputation: 14500

Ehcache provides a way of doing what you want with scheduled refresh.

You will need two things in order to make this work with Ehcache:

  • Use a cache loader - that is move to a cache read-through pattern. This is required as otherwise Ehcache has no idea how to get to the data mapped to a key.
  • Configure scheduled refresh - this works by launching a quartz scheduler instance.

Upvotes: 1

Nassim MOUALEK
Nassim MOUALEK

Reputation: 4864

may be this code could help :

https://github.com/jsr107/jsr107spec/issues/328

Upvotes: 0

cruftex
cruftex

Reputation: 5723

Take a look at RefreshAheadCache, provided by EHCache.

However, I cannot find any examples of its use and indicators that this is mature.

The comment of the class says:

A cache decorator which implements read ahead refreshing. Read ahead occurs when a cache entry is accessed prior to its expiration, and triggers a reload of the value in the background.

This does not directly solve the problem as you mention below:

My problem is how to repopulate the cache without waiting for a read to trigger it

As far as I know there is no standard way to do it. The reason for it, is that the expiry is not timer based.

(Shameless) hint: Since I think this is quite useful, I implemented this in cache2k. The feature is called background refresh, enabled by CacheBuilder.backgroundRefresh(true).

Upvotes: 1

Related Questions