[英]Why doesn't the volatile keyword work as expected in java code?
[英]Volatile doesn't work as expected
所以我正在阅读 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
上次被看到之后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
你能解释一下我错在哪里吗?
提前致谢!
您的观察背后的原因不是 java 中的错误;) 但您的代码中有一个错误。 在你的代码不能保证该调用computeIfPresent
为lastseen
和firstSeen
映射自动执行(参考JavaDocs, computeIfPresent
不是原子)。 这意味着在您获取object.getState().getCounter()
和实际更新地图之间存在时间间隔。
如果设置newCounter
时线程 A 在此间隙(在获得纳米时间之前但已经获得计数器引用 - 旧)和线程 B 在获得object.getState().getCounter()
。 所以如果这个确切的时刻计数器引用被更新,线程 A 将更新旧的计数器键,而线程 B 将更新新的。 如果线程 B 在线程 A 之前花费了纳米时间(这可能发生,因为这些是分离的线程,我们无法知道实际的 cpu 调度是什么),这可能会完全导致您的观察。
我想我的解释很清楚。 还有一件事要澄清,在State
类中,您已经将AtomicInteger counter
声明为 volatile 。 这不是必需的,因为 AtomicInteger 本质上是易变的。 没有“非易失性” Atomic** s。
我只是在您的代码中更改了一些内容以省略上述问题:
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);
}
}
您看到的不是 volatile 的影响,而是同步对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
的相同哈希oldCounter
,然后使用相同的哈希值调用ConcurrentHashMap.computeIfPresent(Integer, ..)
。
由于所有这些线程都尝试更新相同键的值,因此ConcurrentHashMap
必须同步这些更新 - 仅。
在第一个线程更新lastSeen
,主线程执行object.getState().setCounter(newCounter);
,所以第一个线程将执行firstSeen
为newCounter
,而多个线程仍在等待更新lastSeen
。
为了获得更好的结果,最好将信息收集步骤与分析步骤分开。
例如,线程可以将计数器哈希码和更新时间戳捕获到您在所有计算完成后分析的数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.