Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Google Guava Cache refresh exceptions?

Tags:

guava

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?

like image 210
ams Avatar asked Jul 25 '12 01:07

ams


2 Answers

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.

like image 106
Mark Peters Avatar answered Oct 29 '22 08:10

Mark Peters


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

like image 41
fry Avatar answered Oct 29 '22 09:10

fry