Skip to content

Instantly share code, notes, and snippets.

@mishin
Created June 29, 2019 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishin/ce1397638b4c9c6bdd4dd0e39b6d6c2c to your computer and use it in GitHub Desktop.
Save mishin/ce1397638b4c9c6bdd4dd0e39b6d6c2c to your computer and use it in GitHub Desktop.
Listing 5.18. Memoizing Wrapper Using FutureTask.
public class Memoizer3<A, V> implements Computable<A, V> {
private final Map<A, Future<V>> cache
= new ConcurrentHashMap<A, Future<V>>();
private final Computable<A, V> c;
public Memoizer3(Computable<A, V> c) { this.c = c; }
public V compute(final A arg) throws InterruptedException {
Future<V> f = cache.get(arg);
if (f == null) {
Callable<V> eval = new Callable<V>() {
public V call() throws InterruptedException {
return c.compute(arg);
}
};
FutureTask<V> ft = new FutureTask<V>(eval);
f = ft;
cache.put(arg, ft);
ft.run(); // call to c.compute happens here
}
try {
return f.get();
} catch (ExecutionException e) {
throw launderThrowable(e.getCause());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment