在 JCIP 书中,Listing 5.19 存储器的最终实现。我的问题是:
- 由于原子 putIfAbsent() 导致无限的 while 循环在这里?
- while 循环应该在 putIfAbsent() 的 impl 中而不是客户端代码中吗?
- 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());
}
}
}
}