在实践中的Java并发中,第106页,它说“Memoizer3
易受问题影响[两个线程看到空并开始昂贵的计算],因为执行复合操作(如果不存在)使用锁定无法成为原子的支持映射。“我不明白他们为什么说使用锁定不能成为原子。这是原始代码:
package net.jcip.examples;
import java.util.*;
import java.util.concurrent.*;
/**
* Memoizer3
* <p/>
* Memoizing wrapper using FutureTask
*
* @author Brian Goetz and Tim Peierls
*/
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.launderThrowable(e.getCause());
}
}
}
为什么这样的事情不起作用?
...
public V compute(final A arg) throws InterruptedException {
Future<V> f = null;
FutureTask<V> ft = null;
synchronized(this){
f = cache.get(arg);
if (f == null) {
Callable<V> eval = new Callable<V>() {
public V call() throws InterruptedException {
return c.compute(arg);
}
};
ft = new FutureTask<V>(eval);
f = ft;
cache.put(arg, ft);
}
}
if (f==ft) ft.run(); // call to c.compute happens here
...
答案 0 :(得分:1)
当然可以通过使用锁定来实现原子化,想象一下最原始的情况:你对整个函数有一个全局锁定,然后一切都是单线程的,因此是线程安全的。我认为他们意味着别的东西,或者存在普遍的误解。
使用ConcurrentHashMap的putIfAbsent方法甚至可以改善您的代码:
public V compute(final A arg) throws InterruptedException {
Future<V> f = cache.get(arg);
if (f == null) {
final Callable<V> eval = new Callable<V>() {
public V call() throws InterruptedException {
return c.compute(arg);
}
};
final FutureTask<V> ft = new FutureTask<V>(eval);
final Future<V> previousF = cache.putIfAbsent(arg, ft);
if (previousF == null) {
f = ft;
ft.run();
} else {
f = previousF; // someone else will do the compute
}
}
return f.get();
}
最后, f
将是之前添加的值或初始值,以额外创建Callable的潜在成本,但不会多次调用计算