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:
This shot covers insert data, retrieve data, and refresh data.
To use the Guava cache, add the Guava dependency from Maven Repository.
There are two ways to insert data to cache.
put(K, V)
Use the Cache.put
method to insert elements directly. This method overwrites any existing value for the given key.
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>() {@Overridepublic 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"));}}
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.
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.