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;

Cache cache =
        .expireAfterAccess(7, DAYS)

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() {
    public V call() {
        return calculatedValue(key);

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

cache.get(key, () -> {


  • 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 🙂

    Posted August 3, 2016 at 2:38 pm | Permalink

    What about the timeout expiration time in java 8?

  • programming
    Posted September 3, 2018 at 2:06 am | Permalink

    Thank you ffor this interesting post, I have shared it on Twitter.

Post a Reply to philihp Cancel reply

Your email is kept private. Required fields are marked *