Created
March 21, 2013 10:32
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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