Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava LoadingCache: Why use refreshAfterWrite and expireAfterWrite together

I read this document explaining Guava Cache: CachesExplained. I do understand what refreshAfterWrite and expireAfterWrite are doing. However, while explaining refreshAfterWrite, the document also mentions this:

"So, for example, you can specify both refreshAfterWrite and expireAfterWrite on the same cache, so that the expiration timer on an entry isn't blindly reset whenever an entry becomes eligible for a refresh, so if an entry isn't queried after it comes eligible for refreshing, it is allowed to expire."

This is the part that confuses me. For my understanding, if you want a key to be automatically refreshed, you only need to specify refreshAfterWrite. Why do we even want to use expireAfterWrite when ever refreshAfterWrite is used?

like image 413
Z.SP Avatar asked Sep 10 '17 18:09

Z.SP


People also ask

What is expireAfterWrite?

expireAfterWrite(long duration, TimeUnit unit) Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.

How does Guava cache work?

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 LoadingCache thread-safe?

Guava cache is thread safe. The feature provided by Guava cache is basically same as ConcurrentHashMap but Guava cache is more preferable than ConcurrentHashMap in terms of cache optimization.

How does LoadingCache work?

Interface LoadingCache<K,V> A semi-persistent mapping from keys to values. Values are automatically loaded by the cache, 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

There are scenarios in which you'll want the cached entries to be relevant so you set a refresh duration (which might be lighter to perform (and async), rather then a full fetch after eviction and hence, different), but at the same time, if your cache is bounded, you'll want to evict entries, that's what the expireAfterWrite is for. By setting them both, you'll make sure that a entry is evicted after a certain time, even if it was refreshed.

Also note that both are differs in the way they are operate:

Refreshing is not quite the same as eviction. As specified in LoadingCache.refresh(K), refreshing a key loads a new value for the key, possibly asynchronously. The old value (if any) is still returned while the key is being refreshed, in contrast to eviction, which forces retrievals to wait until the value is loaded anew.

like image 116
Shmulik Klein Avatar answered Sep 21 '22 21:09

Shmulik Klein