CacheBuilder

By | March 10, 2017
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

Below one is the nice cache scheme. Just to remind that LoadingCache is an abstract class, not a interface. So it can’t be wrote in lambda expression.

public static void cacheBuilderCase() throws Exception {
    LoadingCache<Integer, String> memo = CacheBuilder.newBuilder().build(
            new CacheLoader<Integer, String>() {
                public String load(Integer key) throws Exception {
                    return String.valueOf(key);
                }
            });

    System.out.println(memo.get(1));
    System.out.println(memo.get(2));
    System.out.println(memo.get(1)); // will get from cache
    System.out.println(memo.get(2)); // will get from cache
}

memo.getIfPresent() return the value. If the value doesn’t exist, it returns null, and it won’t store the value.