In code listing 5.19 of the Brian Goetz book Concurrency In Practice, he presents his finished thread safe Memoizer class.
I thought I understood the code in this example, except that I don't understand what the
while ( true )
is for at the start of the
public V compute(final A arg) throws InterruptedException
method.
Why does the code need the while loop?
Here is the entire code sample
public class Memoizer<A, V> implements Computable<A, V> {
private final ConcurrentMap<A, Future<V>> cache
= new ConcurrentHashMap<A, Future<V>>();
private final Computable<A, V> c;
public Memoizer(Computable<A, V> c) { this.c = c; }
public V compute(final A arg) throws InterruptedException {
while (true) {
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 = cache.putIfAbsent(arg, ft);
if (f == null) { f = ft; ft.run(); }
}
try {
return f.get();
} catch (CancellationException e) {
cache.remove(arg, f);
} catch (ExecutionException e) {
throw launderThrowable(e.getCause());
}
}
}
}
Eternal loop retries on CancellationException. If any other exception is being thrown the execution will be stopped.
Biotext dot org has a blog entry on the same issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With