Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Java caching library or design pattern? [closed]

I need to frequently access the result of a time-consuming calculation. The result changes infrequently, so I have to recalculate the data from time to time but it is ok to use the outdated result for a while. What would be the easiest way to do this and is there an existing library method or design pattern?

I am thinking of something like

private static List myCachedList = null;

...

// refresh list once in 3600 seconds
if (needsRefresh(myCachedList, 3600)) {
    // run the calculation
    myCachedList = ...
}
// use either updated or previous value from here on

A proper implementation might not be trivial, it might have to deal with thread safety, race conditions etc., so I would rather use a proven implementation than roll my own here.

like image 651
nn4l Avatar asked Oct 31 '12 13:10

nn4l


1 Answers

Congratulations for realising that writing your own can be more trouble it initially appears!

I would check out the Guava cache solution. Guava is a proven library and the caches are easily available (and configurable) via a fluent factory API.

All Guava caches, loading or not, support the method get(K, Callable<V>). This method returns the value associated with the key in the cache, or computes it from the specified Callable and adds it to the cache. No observable state associated with this cache is modified until loading completes. This method provides a simple substitute for the conventional "if cached, return; otherwise create, cache and return" pattern.

like image 76
Brian Agnew Avatar answered Sep 21 '22 13:09

Brian Agnew