How to use guava CacheBuilder?

17,988

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.

Share:
17,988

Related videos on Youtube

membersound
Author by

membersound

JEE + Frameworks like Spring, Hibernate, JSF, GWT, Vaadin, SOAP, REST.

Updated on June 04, 2022

Comments

  • membersound
    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 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?

    • Abhijith Nagarajan
      Abhijith Nagarajan over 10 years
      See 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
      Louis Wasserman over 10 years
      It's whatever function you're trying to cache the result of.