Java原子操作

标签 java multithreading atomic

划分下列陈述是正确的:

int v = ++j;

作为:

  1. 读取j值(原子);
  2. 将读取的值加 1 (NON 原子可能干扰 其他线程);
  3. 将相加结果写入i (原子的);
  4. 将 i 写入 v(原子)

最佳答案

是的,int(或更小的数据类型)读/写/算术操作是原子的。引用(读/写)也是原子的,无论它是 32 位还是 64 位。

但是,对 64 位 longdouble 的操作可能不是原子的。

JLS 17.7 Non-atomic Treatment of double and long

Some implementations may find it convenient to divide a single write action on a 64-bit long or double value into two write actions on adjacent 32 bit values. For efficiency's sake, this behavior is implementation specific; Java virtual machines are free to perform writes to long and double values atomically or in two parts.

For the purposes of the Java programming language memory model, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half. This can result in a situation where a thread sees the first 32 bits of a 64 bit value from one write, and the second 32 bits from another write. Writes and reads of volatile long and double values are always atomic. Writes to and reads of references are always atomic, regardless of whether they are implemented as 32 or 64 bit values.

VM implementors are encouraged to avoid splitting their 64-bit values where possible. Programmers are encouraged to declare shared 64-bit values as volatile or synchronize their programs correctly to avoid possible complications.

请注意,前后递增/递减运算符本身都不是原子的,即使在 intbyte 上也不是:读/写/算术操作明显发生单独的步骤。

另见

关于Java原子操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3449790/

相关文章:

swift - 更新从后台线程更改 UI 的变量 - SWIFTUI

c# - 如何在线程中的当前作业完成时中止线程 C#

java - 变量需要声明为final

java - 在Java中计算堆栈中的蜂鸣器数量

java - 在运行时进行 Spring 上下文分析的最先进工具是什么?

multithreading - Scala 的阻塞上下文似乎不适用于混合阻塞/非阻塞作业。为什么?

java - reactor.netty.http.server.AccessLog 产生 LoggingEvent 而不是 AccessEvent

c++ - 为什么在 std::atomic 中使用 volatile 限定符?

multithreading - atomic.Load 和atomic.Store 的意义是什么

python - 确保脚本只被激活一次