gpt4 book ai didi

java - 变量的不同步读/写可能会导致数据竞争?

转载 作者:行者123 更新时间:2023-12-01 21:50:36 27 4
gpt4 key购买 nike

Java Performance Tuning Jack Shirazi 写道:

This means that access and update of variables are automatically synchronized (as long as they are not longs or doubles). If a method consists solely of a variable access or assignment, there is no need to make it synchronized for thread safety, and every reason not to do so for performance. Thread safety extends further to any set of statements that are accessing or assigning to a variable independently of any other variable values.

根据上面的描述,像flag = true这样的操作总是atomic,不需要synchronize

然而,这里来了 another article将以下情况视为数据竞争:


class DataRaceExample {
static boolean flag = false;//w0
static void raiseFlag() {
flag = true;//w1
}
public static void main(String... args) {
ForkJoinPool.commonPool().execute(DataRaceExample::raiseFlag);
while (!flag);//r_i, where i ∈ [1, k), k may be infinite
System.out.print(flag);//r
}
}

作者说:

Now, all executions have data races, because the flag is not volatile

这两篇文章之间的冲突让我很困惑。

最佳答案

Jack Shirazi 错了。

int 等原始变量的访问和更新是原子,但不是同步

因为它是原子的,所以可以通过将其设为volatile 使其完全线程安全。否则,在不同内核上运行的其他线程可能会看到过时值,因为CPU 缓存 尚未刷新。

关于java - 变量的不同步读/写可能会导致数据竞争?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59516745/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com