Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically refresh Cache using Google Guava?

I am using Google Guava library for caching. For automatic cache refresh we can do as follows:

cache = CacheBuilder.newBuilder()                                    .refreshAfterWrite(15, TimeUnit.MINUTES)                     .maximumSize(100)                     .build(....); 

However, automatic refreshes are performed when the first stale request for an entry occurs.

Is there a way to refresh it automatically even though no requests came for cache data? Like for every 15 minutes the cache data should be pulled from Db and load it, no matter whether anybody called cache data or not.

Also, Guava's cache expiry time is for entire cache. Is it possible to expire cache values based on key? Like cache data with key "NOT_SO_FREQ_CHANGE_DATA" to expire for every 1 hour and data with key "FREQ_CHANGING_DATA" should expire for every 15 minutes?

like image 929
K. Siva Prasad Reddy Avatar asked Jul 13 '12 03:07

K. Siva Prasad Reddy


People also ask

How does Guava cache work?

The Guava Cache is an incremental cache, in the sense that when you request an object from the cache, it checks to see if it already has the corresponding value for the supplied key. If it does, it simply returns it (assuming it hasn't expired).

What is guava loading cache?

Advertisements. Guava provides a very powerful memory based caching mechanism by an interface LoadingCache<K,V>. Values are automatically loaded in the cache and it provides many utility methods useful for caching needs.

Is Guava cache thread-safe?

Cache entries are manually added using get(Object, Callable) or put(Object, Object) , and are stored in the cache until either evicted or manually invalidated. Implementations of this interface are expected to be thread-safe, and can be safely accessed by multiple concurrent threads.


1 Answers

Guava provides no way to refresh the cache in bulk, but you can schedule a periodic refresh yourself:

LoadingCache<K, V> cache = CacheBuilder.newBuilder()         .refreshAfterWrite(15, TimeUnit.MINUTES)         .maximumSize(100)         .build(new MyCacheLoader());  for (K key : cache.asMap().keySet()) {     cache.refresh(key); } 

But in that case you may want to override the CacheLoader.reload(K, V) method in MyCacheLoader so it performs asynchronously.

As for the second question, no, you cannot set a per-entry expiration in Guava.

like image 67
Frank Pavageau Avatar answered Oct 01 '22 06:10

Frank Pavageau