Caching with Guava

2019-04-04 01:10发布

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.

3条回答
成全新的幸福
2楼-- · 2019-04-04 01:36

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.

查看更多
Evening l夕情丶
3楼-- · 2019-04-04 01:44

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);
         }
       });
查看更多
Rolldiameter
4楼-- · 2019-04-04 01:47

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.

查看更多
登录 后发表回答