Skip to content

Instantly share code, notes, and snippets.

@sfussenegger
Created March 21, 2013 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sfussenegger/5212107 to your computer and use it in GitHub Desktop.
Save sfussenegger/5212107 to your computer and use it in GitHub Desktop.
A simple Google Guava CacheLoader implementation that submits Function execution to an ExecutorService thus making a LoadingCache asynchronous. Note that threads won't be wasted waiting (at least as long as one doesn't wait on a Future's get() method).
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import com.google.common.base.Function;
import com.google.common.cache.CacheLoader;
public class AsyncCacheLoader<K, V> extends CacheLoader<K, Future<V>> {
private final ExecutorService _executor;
private final Function<K, V> _function;
public AsyncCacheLoader(ExecutorService executor, Function<K, V> function) {
_executor = executor;
_function = function;
}
public Future<V> load(final K key) throws Exception {
return _executor.submit(new Callable<V>() {
public V call() throws Exception {
return _function.apply(key);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment