JCIPブックのリスト5.19Memorizerの最終的な実装。私の質問は次のとおりです。
- アトミックなputIfAbsent()のために、無限のwhileループがここにありますか?
- クライアントコードの代わりにputIfAbsent()のimplのすぐ内側でwhileループを実行する必要がありますか?
- whileループは、putIfAbsent()をラップするだけで、より小さなスコープに含める必要がありますか?
- whileループは読みやすさで悪いように見えます
コード:
public class Memorizer<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 Memorizer(Computable<A, V> c) { this.c = c; }
public V compute(final A arg) throws InterruptedException {
while (true) { //<==== WHY?
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());
}
}
}
}