Implementing a periodically refreshing Cache in Java

Abhishek Jain picture Abhishek Jain · Oct 5, 2012 · Viewed 22.3k times · Source

My use case is to maintain an in-memory cache over the data stored in a persistent DB.

I use the data to populate a list/map of entries on the UI. At any given time, the data displayed on the UI should be as updated as it is possible (well this can be done by the refresh frequency of the cache).

Major difference between a regular cache implementation and this particular cache is that it needs a bulk refresh of all the elements at regular intervals and hence is pretty different from an LRU kind of cache.

I need to do this implementation in Java and it will be great if there are any existing frameworks which can be utilized to get this built around them.

I have explored the Google Guava cache library but it is more suited to a per entry refresh rather than a bulk refresh. There are no simple APIs which do a refresh on the whole cache.

Any help will be highly appreciated.

Also, if it is possible to incrementally do the refresh, it shall be great because the only limitation which arises while refreshing the whole cache is that if the cache is very big in size, then the memory heap should be atleast twice the size of the cache in order to load the new entries and replace the old map with the new one. If the cache is incremental or there is a chunked refresh (refresh in equal sizes) it will be great.

Answer

jtahlborn picture jtahlborn · Oct 5, 2012

EHCache is a pretty full-featured java caching library. i would imagine they have something which would work for you.

In order to do an incremental reload of a cache (which would work on most any cache), just iterate through the currently loaded entries and force refresh them. (you could run this task on a background scheduler).

As an alternative to forcing the entire cache to reload, EHCache has the ability to specify a "time-to-live" for an entry, so entries will automatically be reloaded if they are too stale.