在《Java并发实践》第106页中,它说:“
为什么这样的方法行不通呢?
Memoizer3
容易受到问题的影响[两个线程看到null并开始昂贵的计算],因为在后台地图上执行了一个复合操作(放置-如果缺失),该操作无法使用锁进行原子化。”我不明白为什么他们会说它无法使用锁进行原子化。以下是原始代码: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
...