【发布时间】:2013-05-10 14:45:34
【问题描述】:
我正在从 Brian Goetz 的并发书籍中寻找对以下代码的解释。
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());
}
}
}
另外,在 putIfAbsent() 调用之后,为什么声明 f = ft; 而不仅仅是直接执行 ft.run() ?
【问题讨论】:
-
"我正在寻找对以下代码的解释" => 具体哪一部分你不明白?书中给出的解释有哪些部分你不明白? “为什么声明 f = ft;?” =>
putIfAbsent如果键不存在于地图中,则返回 null。 -
f.get() 会抛出 NullPointerException 而没有 f = ft
标签: java caching concurrency concurrenthashmap