挥发性没有按预期工作

时间:2017-11-28 19:42:32

标签: java multithreading concurrency thread-safety volatile

所以我正在阅读Brian Goetz' JCIP并编写了以下代码来试验volatile行为。

public class StatefulObject {

    private static final int NUMBER_OF_THREADS = 10;

    private volatile State state;

    public StatefulObject() {
        state = new State();
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }

    public static class State {
        private volatile AtomicInteger counter;

        public State() {
            counter = new AtomicInteger();
        }

        public AtomicInteger getCounter() {
            return counter;
        }

        public void setCounter(AtomicInteger counter) {
            this.counter = counter;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        StatefulObject object = new StatefulObject();

        ExecutorService executorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS);

        AtomicInteger oldCounter = new AtomicInteger();
        AtomicInteger newCounter = new AtomicInteger();

        object.getState().setCounter(oldCounter);

        ConcurrentMap<Integer, Long> lastSeen = new ConcurrentHashMap<>();
        ConcurrentMap<Integer, Long> firstSeen = new ConcurrentHashMap<>();
        lastSeen.put(oldCounter.hashCode(), 0L);
        firstSeen.put(newCounter.hashCode(), Long.MAX_VALUE);

        List<Future> futures = IntStream.range(0, NUMBER_OF_THREADS)
            .mapToObj(num -> executorService.submit(() -> {
                for (int i = 0; i < 1000; i++) {
                    object.getState().getCounter().incrementAndGet();
                    lastSeen.computeIfPresent(object.getState().getCounter().hashCode(), (key, oldValue) -> Math.max(oldValue, System.nanoTime()));
                    firstSeen.computeIfPresent(object.getState().getCounter().hashCode(), (key, oldValue) -> Math.min(oldValue, System.nanoTime()));
                }
            })).collect(Collectors.toList());

        executorService.shutdown();

        object.getState().setCounter(newCounter);

        futures.forEach(future -> {
            try {
                future.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });

        System.out.printf("Counter: %s\n", object.getState().getCounter().get());
        long lastSeenOld = lastSeen.get(oldCounter.hashCode());
        long firstSeenNew = firstSeen.get(newCounter.hashCode());
        System.out.printf("Last seen old counter: %s\n", lastSeenOld);
        System.out.printf("First seen new counter: %s\n", firstSeenNew);
        System.out.printf("Old was seen after the new: %s\n", lastSeenOld > firstSeenNew);
        System.out.printf("Old was seen %s nanoseconds after the new\n", lastSeenOld - firstSeenNew);
    }
}

所以我希望newCounter总是在最后一次见到oldCounter后才首次出现(我希望所有线程都注意到更新,所以没有人引用过时的计数器)。为了观察这种行为,我使用了两张地图。但令人惊讶的是,我经常得到这样的输出:

Counter: 9917
Last seen old counter: 695372684800871
First seen new counter: 695372684441226
Old was seen after the update: true
Old was seen 359645 nanoseconds after the new

你能解释一下我错在哪里吗?

提前致谢!

2 个答案:

答案 0 :(得分:1)

观察背后的原因不是java中的错误;)但是代码中有一个错误。在您的代码中,您无法保证对computeIfPresentlastseen映射的firstSeen的调用以原子方式执行(请参阅Javadoc,computeIfPresent不是原子的)。这意味着当你获得object.getState().getCounter()并实际更新地图之间存在时间差。

如果设置newCounter发生在此间隙中的线程A(在获取纳米时间之前但已经获得计数器参考 - 旧)和线程B之前获得object.getState().getCounter()。因此,如果更新了精确时刻计数器参考,则线程A将更新旧计数器密钥,而线程B将更新新计数器密钥。如果线程B在线程A之前占用纳米时间(这可能发生,因为这些是分离的线程,我们无法知道实际的cpu调度是什么),这可能完美地导致您的观察。

我认为我的解释很明确。还有一点要澄清,在State类中,您已将AtomicInteger counter声明为易变。这是不需要的,因为AtomicInteger固有地是易失性的。没有“非挥发性”原子**。

我刚刚在代码中更改了一些内容,以省略上述问题:

import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class StatefulObject {

    private static final int NUMBER_OF_THREADS = 10;

    private volatile State state;

    public StatefulObject() {
        state = new State();
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }

    public static class State {
        private volatile AtomicInteger counter;

        public State() {
            counter = new AtomicInteger();
        }

        public AtomicInteger getCounter() {
            return counter;
        }

        public void setCounter(AtomicInteger counter) {
            this.counter = counter;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        StatefulObject object = new StatefulObject();

        ExecutorService executorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS);

        AtomicInteger oldCounter = new AtomicInteger();
        AtomicInteger newCounter = new AtomicInteger();

        object.getState().setCounter(oldCounter);

        List<Long> oldList = new CopyOnWriteArrayList<>();
        List<Long> newList = new CopyOnWriteArrayList<>();

        List<Future> futures = IntStream.range(0, NUMBER_OF_THREADS)
            .mapToObj(num -> executorService.submit(() -> {
                for (int i = 0; i < 1000; i++) {
                    long l = System.nanoTime();
                    object.getState().getCounter().incrementAndGet();
                    if (object.getState().getCounter().equals(oldCounter)) {
                        oldList.add(l);
                    } else {
                        newList.add(l);
                    }
                }
            })).collect(Collectors.toList());

        executorService.shutdown();

        object.getState().setCounter(newCounter);

        futures.forEach(future -> {
            try {
                future.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });

        System.out.printf("Counter: %s\n", object.getState().getCounter().get());
        Collections.sort(oldList);
        Collections.sort(newList);
        long lastSeenOld = oldList.get(oldList.size() - 1);
        long firstSeenNew = newList.get(0);
        System.out.printf("Last seen old counter: %s\n", lastSeenOld);
        System.out.printf("First seen new counter: %s\n", firstSeenNew);
        System.out.printf("Old was seen after the new: %s\n", lastSeenOld > firstSeenNew);
        System.out.printf("Old was seen %s nanoseconds after the new\n", lastSeenOld - firstSeenNew);
    }
}

答案 1 :(得分:0)

您所看到的不是易失性的影响,而是同步对ConcurrentMap<> lastSeen的影响。

让我们假设所有十个线程几乎同时启动。每个人几乎并行object.getState().getCounter().incrementAndGet();,从而递增oldCounter

接下来,这些线程尝试执行lastSeen.computeIfPresent(object.getState().getCounter().hashCode(), (key, oldValue) -> Math.max(oldValue, System.nanoTime()));。这意味着,它们都会并行评估object.getState().getCounter().hashCode(),每个都获得oldCounter的相同哈希码,然后使用相同的哈希值调用ConcurrentHashMap.computeIfPresent(Integer, ..)

由于所有这些线程都尝试更新同一个键的值,ConcurrentHashMap必须同步这些更新。

在第一个线程更新lastSeen期间,主线程执行object.getState().setCounter(newCounter);,因此第一个线程将为firstSeen执行newCounter,而几个线程仍在执行等待更新lastSeen

为了获得更好的结果,最好将信息收集步骤与分析步骤分开。

例如,线程可以将计数器哈希码和更新的时间戳捕获到您在所有计算完成后分析的数组中。