This page will walk through Google Guava cache example using LoadingCache, CacheBuilder and CacheLoader. Guava cache stores key and object like ConcurrentHashMap. Guava cache is thread safe. The feature provided by Guava cache is basically same as ConcurrentHashMap but Guava cache is more preferable than ConcurrentHashMap in terms of cache optimization. Find some features of Guava cache.

1. We can define maximum capacity of cache to store key/object.
2. We can set expiry time of cache.
3. We can configure listener that listens any removal of cache element.
4. We can configure concurrency level.

LoadingCache&ltK,V&gt

K: Base key type.
V: Base value type.

com.google.common.cache.LoadingCache loads data in cache automatically. Data remains in cache until it is evicted or cache is invalidated. LoadingCache is thread safe. This class provides different methods to access data for the given key. Some methods of this class are get(K key), asMap(), getUnchecked(K key), refresh(K key).

CacheBuilder&ltK,V&gt

com.google.common.cache.CacheBuilder is the builder for LoadingCache. Using CacheBuilder, we can configure cache settings. Find some methods of this class.

concurrencyLevel(int concurrencyLevel) : It sets concurrency level among update operations.
expireAfterAccess(long duration, TimeUnit unit) : We set the time to expire and once time is up, cache is expired after most resent access.
expireAfterWrite(long duration, TimeUnit unit) : Cache is expired in a given duration after most resent write.
maximumSize(long size) : Maximum size of entries that cache can store.
removalListener(RemovalListener&lt? super K1,? super V1&gt listener) : Sets the listener that listens when any entry is removed.

CacheLoader&ltK,V&gt

com.google.common.cache.CacheLoader loads values for the given key and is cached with LoadingCache. We need to override load(K key) that returns the object to be cached. Within load(K key) method, we call our method which output needs to be cached. Normally we need to cache the output of the methods that performs some expensive calculation or database access which is being retrieved frequently.