为什么Java Concurrency In Practice清单5.18不能用锁定原子方式完成?

Pet*_*Pro 7 java concurrency

在Java Concurrency in Practice中,第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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么这样的东西不起作用?

...
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
    ...
Run Code Online (Sandbox Code Playgroud)

Two*_*The 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();
}
Run Code Online (Sandbox Code Playgroud)

f最后将是之前添加的值或初始值,但可能会额外创建 Callable,但不会多次调用计算。