Looking for simple Java in-memory cache

Ehcache is a pretty good solution for this and has a way to peek (getQuiet() is the method) such that it doesn't update the idle timestamp. Internally, Ehcache is implemented with a set of maps, kind of like ConcurrentHashMap, so it has similar kinds of concurrency benefits.


If you're needing something simple, would this fit the bill?

Map<K, V> myCache = Collections.synchronizedMap(new WeakHashMap<K, V>());

It wont save to disk, but you said you wanted simple...

Links:

  • Collections.synchronizedMap
  • WeakHashMap

(As Adam commented, synchronising a map has a performance hit. Not saying the idea doesn't have hairs on it, but would suffice as a quick and dirty solution.)


Since this question was originally asked, Google's Guava library now includes a powerful and flexible cache. I would recommend using this.

Tags:

Java

Caching