Simple Java caching library or design pattern?

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.


I would suggest for you to use the Proxy Design Pattern that way you can encapsulate the caching logic-implementation in your proxy class

theres a cool example here that looks like to fit your needs

http://en.wikipedia.org/wiki/Proxy_pattern


I would take a look at Google guava-libraries. Much of this work has already been done for you.

There's specifically a section called Timed Eviction, which might be related to what you want. https://github.com/google/guava/wiki/CachesExplained#timed-eviction