_Original issue created by electrum on 2013-12-30 at 09:30 PM_
The documentation for CacheLoader.refreshAfterWrite() recommends overriding reload() with an asynchronous version. We use the following in many places and think it could be a good addition to Guava:
public abstract class BackgroundCacheLoader<K, V>
extends CacheLoader<K, V>
{
private final ListeningExecutorService executor;
protected BackgroundCacheLoader(ListeningExecutorService executor)
{
this.executor = checkNotNull(executor, "executor is null");
}
@Override
public final ListenableFuture<V> reload(final K key, V oldValue)
throws Exception
{
return executor.submit(new Callable<V>()
{
@Override
public V call()
throws Exception
{
return load(key);
}
});
}
}
_Original comment posted by [email protected] on 2013-12-30 at 09:35 PM_
We have this internally as CacheLoaders.asyncReload. It has about 40 callers. Anyone object to releasing it? Perhaps we should move it to CacheLoader itself, since we've been avoiding creating "Foos" utility types when Foo is an abstract class?
Status: Research
Labels: Type-Addition, Package-Cache
_Original comment posted by [email protected] on 2013-12-30 at 09:36 PM_
In the meantime:
public static <K, V> CacheLoader<K, V> asyncReload(final CacheLoader<K, V> loader,
final Executor executor) {
checkNotNull(loader);
checkNotNull(executor);
return new CacheLoader<K, V>() {
@锘縊verride
public V load(K key) throws Exception {
return loader.load(key);
}
@Override
public ListenableFuture<V> reload(final K key, final V oldValue) throws Exception {
ListenableFutureTask<V> task = ListenableFutureTask.create(new Callable<V>() {
@Override
public V call() throws Exception {
return loader.reload(key, oldValue).get();
}
});
executor.execute(task);
return task;
}
@Override
public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
return loader.loadAll(keys);
}
};
}
_Original comment posted by [email protected] on 2014-01-03 at 09:01 PM_
Thumbs up...it has seen good adoption internally.
Status: Started
Owner: [email protected]
You should totally update the Caches Explained wiki to mention this API! :100:
Any examples on how to use asyncReloading?
I'm using CacheBuilder with Spring cache.
Presumably it's automagically creating a default LoadingCache somewhere along the way to the @Cacheable but it'd be nice to configure a cache that does async reloading without having to override CacheLoader.reload()
Most helpful comment
You should totally update the Caches Explained wiki to mention this API! :100: