Guava LoadingCache: Why use refreshAfterWrite and expireAfterWrite together

20.4k views Asked by At

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?

1

There are 1 answers

7
Shmulik Klein On BEST ANSWER

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.