philihpAboutPGPLightning

Using Java 8 Lambdas with Google Guava Caches

Philihp Busby,1 min read

With Guava, you can define a simple in-memory cache with

import static java.util.concurrent.TimeUnit.DAYS; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; Cache<K, V> cache = CacheBuilder.newBuilder() .maximumSize(100000) .expireAfterAccess(7, DAYS) .build();

With this you can use .put(K, V) to load values, and .getIfPresent(K), which returns null if the key isn't present. Sometimes it's more convenient to use get(K key, Callable<? extends V> valueLoader) , where the valueLoader is called on a cache miss, and populates the cache and gives you what a cache hit would have given you. The old Java 7 way  of doing this was really ugly:

cache.get(key, new Callable() { @Override public V call() { return calculatedValue(key); } });

Don't write ugly code . With Java 8 Lambdas, just do this:

cache.get(key, () -> { calculatedValue(key); }

GitHub · Bluesky · LinkedIn · Instagram · KeybaseRSS

Built from 8f0906ac CC BY 4.0 — with love from San Francisco.