capint
9/11/2016 - 4:22 PM

Java >> Guava >> LoadingCache

Java >> Guava >> LoadingCache

//Source: http://www.tutorialspoint.com/guava/guava_caching_utilities.htm
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.google.common.base.MoreObjects;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public class GuavaTester {
 public static void main(String args[]) {
 
    //create a cache for employees based on their employee id
    LoadingCache<String, Employee> employeeCache = 
       CacheBuilder.newBuilder()
          .maximumSize(100) // maximum 100 records can be cached
          .expireAfterAccess(30, TimeUnit.MINUTES) // cache will expire after 30 minutes of access
          .build(new CacheLoader<String, Employee>(){ // build the cacheloader
              //*** Override this method to tell which expensive operation to call
             @Override
             public Employee load(String empId) throws Exception {
                //make the expensive call
                return getFromDatabase(empId);
             } 
          });

    try {			
       //*** on first invocation, cache will be populated with corresponding
       //employee record
       System.out.println("Invocation #1");
       System.out.println(employeeCache.get("100"));
       System.out.println(employeeCache.get("103"));
       System.out.println(employeeCache.get("110"));
       
       //*** second invocation, data will be returned from cache, the expensive operation won't be called
       System.out.println("Invocation #2");
       System.out.println(employeeCache.get("100"));
       System.out.println(employeeCache.get("103"));
       System.out.println(employeeCache.get("110"));

    }catch (ExecutionException e) {
       e.printStackTrace();
    }
 }
}