Created
June 29, 2019 08:43
-
-
Save mishin/ce1397638b4c9c6bdd4dd0e39b6d6c2c to your computer and use it in GitHub Desktop.
Listing 5.18. Memoizing Wrapper Using FutureTask.
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
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