划分下列陈述是正确的:
int v = ++j;
作为:
- 读取j值(原子);
- 将读取的值加 1 (NON 原子可能干扰 其他线程);
- 将相加结果写入i (原子的);
- 将 i 写入 v(原子)
最佳答案
是的,int
(或更小的数据类型)读/写/算术操作是原子的。引用(读/写)也是原子的,无论它是 32 位还是 64 位。
但是,对 64 位 long
和 double
的操作可能不是原子的。
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
ordouble
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 tolong
anddouble
values atomically or in two parts.For the purposes of the Java programming language memory model, a single write to a non-
volatile
long
ordouble
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 ofvolatile long
anddouble
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.
请注意,前后递增/递减运算符本身都不是原子的,即使在 int
或 byte
上也不是:读/写/算术操作明显发生单独的步骤。
另见
关于Java原子操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3449790/