简单getter调用volatile变量原子操作?
Is simple getter call on volatile variable atomic operation?
我的 class 中有以下内容:
private static volatile byte counter = 0;
public static byte getCounter() {return counter;}
对 getCounter
的调用是原子的还是非原子的?
是的,这是一个原子操作,从某种意义上说,没有重新排序或计时会导致字节在部分写入时被读取。如果字节在读取时被重新分配,则 getter 保证为 return 之前或之后的值,但 没有其他值 ,即使没有 volatile
.
但是,您必须 volatile
double 或 long 值以避免读取既不是旧值也不是新值的不一致读取:
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.
Implementations of the Java Virtual Machine are encouraged to avoid splitting 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.
我的 class 中有以下内容:
private static volatile byte counter = 0;
public static byte getCounter() {return counter;}
对 getCounter
的调用是原子的还是非原子的?
是的,这是一个原子操作,从某种意义上说,没有重新排序或计时会导致字节在部分写入时被读取。如果字节在读取时被重新分配,则 getter 保证为 return 之前或之后的值,但 没有其他值 ,即使没有 volatile
.
但是,您必须 volatile
double 或 long 值以避免读取既不是旧值也不是新值的不一致读取:
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.
Implementations of the Java Virtual Machine are encouraged to avoid splitting 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.