Search code examples
javacaffeine-cache

Retain old value when refreshing cache?


I have a Caffeine AsyncLoadingCache created with a refreshAfterWrite configured. For a given key, if a value is already loaded into the cache and there is an error during refresh, the key/value gets removed. Instead of this, I would like to retain the old value and update the expiration timestamp so it doesn't immediately get refreshed again. Is there a way to configure this behavior?


Solution

  • You can implement either CacheLoader.reload(key, oldValue) or AsyncCacheLoader.asyncReload(key, oldValue). When an error occurs it shouldn't remove the old value but can be triggered again on the next call. If the result resolves to null then it should be removed. Since the old value is provided, if returned then it would reset the timestamps as desired.