Using Java 8 Lambdas with Google Guava Caches

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 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);
}

3 Comments

  • Taylor
    Posted October 17, 2015 at 11:22 pm | Permalink

    Will you please contact me I have some questions about a hula hoop project I’m doing for my wife thank you , peace

    • philihp
      Posted November 8, 2015 at 6:07 am | Permalink

      Emailed! Please feel free to comment directly on that blog post 🙂

  • anon@anon.com
    Posted August 3, 2016 at 2:38 pm | Permalink

    What about the timeout expiration time in java 8?

Post a Comment

Your email is kept private. Required fields are marked *