Sunday, September 14, 2014

In-Process Caching Using Google Guava

Introduction

In many enterprise applications, in particular, those involving database retrievals, to obtain objects from sources like database for every filtering, sorting, is expensive, slow, sometimes, impractical. Therefore, caching is a preferred solution. There are two categories of caching with regards to application address spaces, in-process and distributed. This article provides a tutorial for using Google Guava's library for in-process caching. For distributed caching, the memcachedached is popular solution. Ehcache from Terracotta is a product that can be configured to function both for in-process and distributed caching.

The source code for this tutorial can be found at my GitHub repository at Guava-Cache Project

Project Dependency

In order to use the Google Guava API, we need to add the following maven dependency to our project:
  
      com.google.guava
      guava
      17.0
  

Google Guava API

The caching interface is named LoadingCache in the following form:

public interface LoadingCache extends Cache, Function
{
    V get(K key) throws ExecutionException;
    V getUnchecked(K key);
    ImmutableMap getAll(Iterable keys) 
        throws ExecutionException;
    void refresh(K key);
    ConcurrentMap asMap();
}

This interface inherit the Cache interface which has the following methods:

public interface Cache {
     @Nullable
     V getIfPresent(Object key);
     V get(K key, Callable valueLoader) throws ExecutionException;
     ImmutableMap getAllPresent(Iterable keys);
     void put(K key, V value);
     void putAll(Map m);
     void invalidate(Object key);
     void invalidateAll(Iterable keys);
     void invalidateAll();
     long size();
     ConcurrentMap asMap();
     void cleanUp();
}

Put API In Use

The use cases for caching, typically, are:
  • add key - value pair
  • add more then one key-value pairs
  • retrive by key
  • retrive multiple values by multiple keys
  • retrive all
  • refereshing
  • clear the caching
  • Instantiate A Cache

    Here is the snippet on how to instantiate a cache instance. In spring framework, you can let the framework to take care the instantiation, but the gist is the same:

    	private LoadingCache> cache;
    	
    	private EmployeeDao employeeDao;
    	
    	public CachingWithGuava () {
    		this.init();
    	}
    	
    	private void init() {
    		
    		CacheLoader> loader = new EmployeeCacheLoader();
    
    		cache = CacheBuilder.
    				newBuilder().
    				maximumSize(1000).
    				expireAfterWrite(1L, TimeUnit.DAYS).
    				expireAfterAccess(1, TimeUnit.DAYS).
    				build(loader);
    		
    		this.employeeDao = new EmployeeDao();
    	}
    

    In the about code, I define the cache for maximum size of 1000, and the other eviction policy, say, expire after 1 day of writing, expire after 1 day of access. The loader define how to load the entries to the cache as explained in the next section.

    Put Key-Value Pair To Cache

    You may first think to use put(K, V) method. This is really not correct way. Guava API provides a CacheLoader abstract class. We can extend this by proving implementation of load methods as the following:

    public class EmployeeCacheLoader extends CacheLoader>{
    	private EmployeeDao employeeDao;
    	
    	public EmployeeCacheLoader() {
    		this.employeeDao = new EmployeeDao();
    	}
    	
    	@Override
    	public Optional load(String name) throws Exception {
    		return Optional.fromNullable(employeeDao.getEmployeeByName(name));
    	}
    
    }
    
    

    The load method defines how we put the K-V pair into cache if the K-V does not present in the cache.

    Clearing Cache

    Guava API provides few option to clear caching as the following:
    • invalide(key): clear single cache by the key
    • invalide(keys): clear multiple cache by keys
    • invlideAll(): clear all caches>

    Sometimes, we may need to clear all caches based scheduling. In that case, Apache Camel's timer or Quartz api can be considered.

    References

    1. Google Official: guava-libraries

2 comments:

  1. http://www.javaproficiency.com/2015/05/guava-cache-memory-example.html

    ReplyDelete
  2. Thanks for sharing nice example visit more good example
    Guava Cache Example

    ReplyDelete

Anypoint Studio Error: The project is missing Munit lIbrary to run tests

Anypoint Studio 7.9 has a bug. Even if we following the article: https://help.mulesoft.com/s/article/The-project-is-missing-MUnit-libraries-...