Java Volatile的双重含义

http://www.ibm.com/developerworks/cn/java/j-jtp06197.html

 Volatile 的含义包含以下两层意思:

  1. 多个线程每次读取的volatile变量值都是最新的,即便该变量值是被其他线程设置
  2. JDK5 and later extends the semantics for volatile so that the system will not allow a write of a volatile to be reordered with respect to any previous read or write, and a read of a volatile cannot be reordered with respect to any following read or write (from http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
 

使用Volatile需要注意的两点:

  1. 对变量的写操作不依赖于当前值。
  2. 该变量没有包含在具有其他变量的不变式中。
此处,不变式的含义,我的理解是volatile变量生命周期内,永远成立的关系表达式(如理解有误,还望指出)。这两点的出处源于:http://www.ibm.com/developerworks/cn/java/j-jtp06197.html

原文地址:https://www.cnblogs.com/daition/p/2498534.html