Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching with Guava

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.

like image 492
maaartinus Avatar asked Jan 19 '11 10:01

maaartinus


People also ask

What is Guava caching?

The Guava Cache is an incremental cache, in the sense that when you request an object from the cache, it checks to see if it already has the corresponding value for the supplied key. If it does, it simply returns it (assuming it hasn't expired).

Is Guava cache thread safe?

Cache entries are manually added using get(Object, Callable) or put(Object, Object) , and are stored in the cache until either evicted or manually invalidated. Implementations of this interface are expected to be thread-safe, and can be safely accessed by multiple concurrent threads.

What is Google common cache?

cache Description. This package contains caching utilities. The core interface used to represent caches is Cache . In-memory caches can be configured and created using CacheBuilder , with cache entries being loaded by CacheLoader .


1 Answers

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);
         }
       });
like image 196
KARASZI István Avatar answered Nov 04 '22 17:11

KARASZI István