title: Asynchronous Cache Update With Spring Cache Abstraction
body: <p>Using Spring's caching abstraction, how can I have a cache refresh an entry asynchronously while still returning the old entry?</p>
  
  <p>I am trying to use Spring's caching abstraction to create a caching system where after a relatively short "soft" timeout, cache entries are made eligible for refresh. Then, when they are queried, the cached value is returned, and an asynchronous update operation is started to refresh the entry. I would also </p>
  
  <p>Guava's cache builder allows me to specify that entries in the cache should be refreshed after a certain amount of time. The reload() method of the cache loader can then be overridden with an asynchronous implementation, allowing the stale cached value to be returned until the new one is retrieved. However, spring caching seems to not use the CacheLoader of an underlying Guava cache</p>
  
  <p>Is it possible to do this kind of asynchronous cache refresh using Spring's caching abstraction?</p>
  
  <p>Edit to clarify:
  With Guava's CacheBuilder I can use refreshAfterWrite() to get the behaviour I want. e.g. from <a href="https://code.google.com/p/guava-libraries/wiki/CachesExplained" rel="noreferrer">Guava Caches Explained</a>:</p>
  
  <pre><code>LoadingCache&lt;Key, Graph&gt; graphs = CacheBuilder.newBuilder()
     .maximumSize(1000)
     .refreshAfterWrite(1, TimeUnit.MINUTES)
     .build(
         new CacheLoader&lt;Key, Graph&gt;() {
           public Graph load(Key key) { // no checked exception
             return getGraphFromDatabase(key);
           }
  
           public ListenableFuture&lt;Graph&gt; reload(final Key key, Graph prevGraph) {
             if (neverNeedsRefresh(key)) {
               return Futures.immediateFuture(prevGraph);
             } else {
               // asynchronous!
               ListenableFutureTask&lt;Graph&gt; task = ListenableFutureTask.create(new Callable&lt;Graph&gt;() {
                 public Graph call() {
                   return getGraphFromDatabase(key);
                 }
               });
               executor.execute(task);
               return task;
             }
           }
         });
  </code></pre>
  
  <p>However, I cannot see a way to get the behaviour of refreshAfterWrite() using Spring's @Cacheable abstraction.</p>