What Guava classes are suitable for thread-safe caching? I use a composed key, which gets constructed on the fly, so softKeys() makes no sense, right? I saw somewhere ConcurentLinkedHashMap, is it the way to go? Is it already in the recent release? Sorry for the chaotic way of asking...
Update
This question is pretty old and looking through he answers could possible be a waste of time. Since long there's a CacheBuilder
which is the way to go.
Sounds like you want MapMaker.makeComputingMap
, but you mention softKeys
so I assume you are already familiar with that class.
You are right about softKeys
- it will not work if you compose keys on-the-fly, because softKeys
causes the map to use ==
instead of equals
for key comparison. But you should be fine with softValues
and expiration
, as long as there is no side-effect from recreating an evicted entry.
The new Guava library with version 10.0 introduces the Cache
interface which is designed especially for caching.
It comes with CacheBuilder
, which is similar to MapMaker
and all caching methods of MapMaker
will be removed in the release 11.
Example from the documentation:
Cache<Key, Graph> graphs = CacheBuilder.newBuilder()
.concurrencyLevel(4)
.weakKeys()
.maximumSize(10000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(
new CacheLoader<Key, Graph>() {
public Graph load(Key key) throws AnyException {
return createExpensiveGraph(key);
}
});
MapMaker.maximumSize()
is the long-term replacement for ConcurrentLinkedHashMap
. CLHM remains the test-bed for improved algorithms for later porting if there is community consensus. I expect v2.0 will be the last release after porting those improvements to MapMaker
, though. The project will remain alive as needed since it has a good user base (e.g. Apache Cassandra). I'm quite happy that Guava subsumed it.