Java的long、double类型的原子性读取问题
In programming, an atomic action is one that effectively happens all at once. An atomic action cannot stop in the middle: it either happens completely, or it doesn’t happen at all. No side effects of an atomic action are visible until the action is complete.
以上是关于原子性的操作的相关描述。
在Java中,以下的操作可以认为是原子操作
- 对于引用变量、大多数的原始类型变量的读、写(所有的类型除了
long
和double
)都是原子性的(这个只有才32位的JVM成立) - 所有申明为
volatile
的变量(包括long
和double
变量)的读、写都是原子性的
在Java中,自增、自减操作都不是原子性操作,很容易理解。但是long
和duoble
的读写却不是原子性的问题,却不太好理解。
检验
在32位JVM上,通过两个线程对同一个成员变量进行读写,来测试long
和double
类型变量的读写不是原子性操作。