membersound
membersound

Reputation: 86637

How to use guava CacheBuilder?

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 a HashMap<Key, Value> mapping? What do I have to do with the key value?

Or could I also just return a List<String> in this method not having to use the key value in any way?

Upvotes: 7

Views: 18686

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328556

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.

Upvotes: 19

Related Questions