How to use guava CacheBuilder?
The idea of the cache is that you usually have this problem:
Graph get(Key key) {
Graph result = get( key );
if( null == result ) {
result = createNewGraph( key );
put( key, result );
}
return result;
}
plus the usual synchronization issues that you have when you use this code in a multi-threaded environment.
Guava does the boilerplate for you; you just have to implement createNewGraph()
. The way Java works, this means you have to implement an interface. In this case, the interface is CacheLoader
.
If you think that the whole cache is a bit like a map, then CacheLoader
is a callback that gets invoked whenever a key can't be found in the map. The loader will get the key (because it usually contains useful information to create the object that is expected for this key) and it will return the value which get()
should return in the future.
Related videos on Youtube
membersound
JEE + Frameworks like Spring, Hibernate, JSF, GWT, Vaadin, SOAP, REST.
Updated on June 04, 2022Comments
-
membersound almost 2 years
I'd like to use guavas
CacheBuilder
, but cannot find any explicit example how implement this.The docs state the following code:
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder() .maximumSize(1000) .build( new CacheLoader<Key, Graph>() { public Graph load(Key key) throws AnyException { return createExpensiveGraph(key); } });
Question: what is this
createExpensiveGraph(key)
method? Is this a method that returns aHashMap<Key, Value>
mapping? What do I have to do with thekey
value?Or could I also just return a
List<String>
in this method not having to use thekey
value in any way?-
Abhijith Nagarajan over 10 yearsSee the api of CacheLoader and load method which gives clear meaning of why the method is used? docs.guava-libraries.googlecode.com/git/javadoc/com/google/… createExpensiveGraph does not return hashMap instead return a object of Graph.
-
Louis Wasserman over 10 yearsIt's whatever function you're trying to cache the result of.
-