Trusted answers to developer questions

How to insert, retrieve, and refresh Guava Cache

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

The Guava project is a collection of several of Google’s core libraries for string processing, caching, etc. Guava Cache is an in-memory cache used in applications.

The following operations can be performed on a cache:

  1. Insert data
  2. Retrieve data
  3. Refresh data
  4. Listen to changes in cache
  5. Evict/remove data
  6. Statistics of operations in cache

This shot covers insert data, retrieve data, and refresh data.

To use the Guava cache, add the Guava dependency from Maven Repository.

Insert data

There are two ways to insert data to cache.

1. put(K, V)

Use the Cache.put method to insert elements directly. This method overwrites any existing value for the given key.

2. via a CacheLoader

The get(K) method on the cache will either return the cached value or use the CacheLoader defined to load a new value to the cache.

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.concurrent.ExecutionException;
public class Main {
public static void main(String[] args) throws ExecutionException {
LoadingCache<String, Integer> cache = CacheBuilder.newBuilder().build(new CacheLoader<String, Integer>() {
@Override
public Integer load(String key) {
return key.length();
}
});
cache.get("hello");
cache.put("hi", 2);
System.out.println(cache.get("hello"));
System.out.println(cache.get("hi"));
}
}

Retrieve data from the cache

Method Description
.get(K) Retrieves the value for a given key.
.getAll(Iterable) Retrieves the value for a list of keys. Here, if a key is not present, then the value will be computed using the CacheLoader defined.
getIfPresent(K) Returns the value if present. Otherwise, it returns null.

To extend the code above, add the following.

System.out.println(cache.getIfPresent("hello"));

would return 5.

System.out.println(cache.getIfPresent("mattress"));

would return null, as the key is not present in the cache.

Refresh the cache

Cache refresh refers to when all the values for all the keys in the cache are recomputed.

Method Description
.refresh(K) Loads a new value for the key.
CacheBuilder.refreshAfterWrite(Duration) The active keys in the cache are eligible for automatic refresh once a fixed duration has elapsed after the key’s creation, or the most recent replacement of its value.

To extend the code above, add the following.

cache.refresh("hello");

would recompute the value for the hello key.

RELATED TAGS

java
guava
cache
Did you find this helpful?