Skip to Content

LoadingCache in Java 8 without Guava

Since Guava library was released, I’ve been a huge fan of MapMaker, later renamed to CacheBuilder. The feature I prefer is the LoadingCache.

Here’s an extract from Guava’s wiki:

LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
       .build(
           new CacheLoader<Key, Graph>() {
             public Graph load(Key key) throws AnyException {
               return createExpensiveGraph(key);
             }
           });

Basically, what it does is instantiate a ConcurrentHashMap that computes its values on demand. Call graps.get(aKey) and the load(key) method will be invoked with aKey in argument. The resulting value will be stored into the Map. Next time graps.get(aKey) is called, the value will be returned directly from the cache. That’s nice! All this completely thread safe!

With Java 8, you can do the same with a very elegant syntax:

ConcurrentMap<Key, Graph> map = new ConcurrentHashMap<>();
map.computeIfAbsent(aKey, key -> createExpensiveGraph(key));

Nice isn’t it?

The second argument is a lambda that tells the map how to create the value from a key. Unlike inner classes, using a lambda adds no noticeable cost to the method call.

It’s not as good as the CacheBuilder in terms of expiry management, yet it’s really simple and nice to use.

comments powered by Disqus