6
votes

The Google Guava Cache documentation states:

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.

If an exception is thrown while refreshing, the old value is kept, and the exception is logged and swallowed.

This logging and swallowing of exceptions is really bad in my use case, because it means that if refresh throws an exception users of the cache will continue to find the stale data in the Cache.

How can I make sure that if an exception is thrown in refresh the cache starts returning null or calling load method?

2

2 Answers

8
votes

If you never want to serve the stale data, you should call invalidate(key) instead of refresh(key). This discards the cached value for key, if one exists.

Then a subsequent call to get(key) will delegate synchronously to the value loader, and will rethrow any exception thrown by the CacheLoader, wrapped in an (Unchecked)ExecutionException.

1
votes

If stale data is a problem for you then you should use expireAfterWrite to ensure that stale data is never served.