Search code examples
javacachingguava

Is it possible to configure Guava Cache (or other library) behaviour to be: If time to reload, return previous entry, reload in background (see specs)


I'd like to have a cache that works like this:

  • A. If request is not cached: load and return results.
  • B. If request is cached, has not expired: return results.
  • C. If request is cached, has expired: return old results immediately, start to reload results (async)
  • D. If request is cached, has expired, reload is already running: return old results immediately.
  • E. If reloading fails (Exception): continue to return previous successful load results to requests.

(After a failed reload (case E), next request is handled following case C.)

(If case A ends in Exception, Exception is thrown)

Does anyone know an existing implementation, or will I have to implement it myself?


Solution

  • https://github.com/ben-manes/caffeine

    Caffeine provides exactly the behavior I want out of the box using refreshAfterWrite:

    LoadingCache<K, V> cache = Caffeine.newBuilder()
       .refreshAfterWrite(expireTime, timeUnit)
       .maximumSize(maxCountOfItems)
       .build(k->loader.load(k));