How to handle Google Guava cache update exceptions?

The documentation for the Google Guava cache states:

Updating is not exactly the same as eviction. As stated in LoadCache.refresh (K), updating a key loads a new value for the key, possibly asynchronously. The old value (if any) is still returned while the key is being updated, as opposed to eviction, which causes search engines to wait until the value is reloaded.

If an exception is selected during the upgrade, the old value is saved and the exception is logged and swallowed.

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

How can I make sure that if an exception occurs during the upgrade, the cache starts returning a null or calling boot method?

+5
source share
2 answers

If you never want to use stale data, you should call invalidate(key)instead refresh(key). This discards the cached value for keyif it exists.

Then the subsequent call get(key)will be delegated synchronously with the value loader and will throw any exception thrown CacheLoader, wrapped in (Unchecked)ExecutionException.

+7
source

If outdated data is a problem for you, you should use expireAfterWriteto ensure that outdated data will never be served.

+1
source

All Articles