Sunday, August 3, 2014

Google Guava CacheBuilder

This cache is mainly used where

  • Where the same data is retrieved multiple times
  • Where the time required to access the data to be small
  • Cache size is limited and known

How to create

Cache to be created with or without CacheLoader. We will see only with CacheLoader. LoadingCache is the Cache implementation that can be created using CacheBuilder and add some properties to it and include CacheLoader to it.
         LoadingCache<String, Person> persons = CacheBuilder.newBuilder() 
Here Person is the object stored in Cache using key of type String. loader is the CacheLoader. See below on how to create
        CacheLoader loader = new CacheLoader()
            public Person load(String key) throws Exception
                return getPerson(key);
Loader has to be created with load method implemented with the basic operation on on how to load the object using the key.


CacheBuilder defines the properties of the cache like

  • Initial capacity: Initial capacity of the cache
  • Maximum size: The maximum size of the cache and the cache evicts the object before the size is reached.
  • Expire after access: Cache automatically removes the entry once the time is elapsed after the last access.
  • Expire after write: Cache automatically removes the entry once the time is elapsed after the last write.
  • Refresh after write: Cache retrieves the data and refreshes once the time is elapsed using load.
  • Record stats : Once this is called, the stats will be recorded on the cache and returns the status when called stats() method.

How to create CacheBuilder

Calling methods explicitly

Call each of the following methods on the CacheBuilder to set the properties 
LoadingCache<String, Person> persons = CacheBuilder.newBuilder()
                .refreshAfterWrite(20, TimeUnit.HOURS)
                .expireAfterAccess(1, TimeUnit.DAYS)

Using CacheBuilderSpec

Set all the parameters in a string comma delimited in CacheBuilderSpec and pass to CacheBuilder.from(spec) to build the cache with the parameters
CacheBuilderSpec spec = CacheBuilderSpec
        LoadingCache<String, Person> p2 = CacheBuilder.from(spec).build(loader);

How to Access

Accessing the objects in the cache are simple using get and put methods as a HashMap.

Sample Code

        Person p = new Person();
        p.setLocation("New Yrok");
        persons.put("P1", p);

        System.out.println("Size of Cache is : " + persons.size());

        Person p1 = new Person();
        p1.setLocation("New Jersy");
        persons.put("P2", p1);

        System.out.println("Size of Cache is : " + persons.size());

        Person d1 = persons.get("P1");
        System.out.println("Person is : " + d1.getName());

        System.out.println("Size of Cache is : " + persons.size());

Output will be

Size of Cache is : 1
Size of Cache is : 2
Person is : Joe
Size of Cache is : 2

Evict an object

There are different ways of evict options
Timed Eviction: Use the methods expireAfterAccess and expireAfterWrite to evict automatically after the time elapsed
Explicit Eviction:  Use the method invalidate(String) to evict one object with the given key and use invalidateAll to remove all.

Other Features

There are other important features that we can make use of when required.

Cache Stats

The cache can record stats when we explicitly call recordStats (Default is off). Once switched on, the stats() method returns the status like
  • Load Count
  • Load Exception Count
  • Load Success Count
  • Eviction Count
  • Hit rate
  • Miss rate etc.


The complete cache can be returned as map with key and values.

No InterruptedException

The cache doesn't throw InterruptedException but they are designed to make it throw. (But the documentation says (We could have designed these methods to support InterruptedException, but our support would have been incomplete, forcing its costs on all users but its benefits on only some.)

Happy Learning!!!