...
| Wiki Markup |
|---|
2. [Sequential consistency|BB. Definitions#sequential consistency]: "The fact that we allow a read to see a write that comes later in the execution order can sometimes thus result in unacceptable behaviors." \[[JLS 05|AA. Java References#JLS 05]\]. In such cases, sequential consistency is required. This condition ensures that the compiler does not optimize away or reorder any statements. It also ensures that each operation is atomic and immediately visible to other threads. This makes it easy for a programmer to follow the logic, however, introduces a performance penalty. Synchronization guarantees sequential consistency and so does use of the {{volatile}} keyword. |
A write to a volatile field happens-before every subsequent read of that field. Declaring a variable volatile guarantees the happens-before relationship so that writes are always visible to subsequent reads from any thread. It also ensures sequential consistency, in that, volatile read and write operations cannot be reordered with respect to each other and in addition, as required by the modern JMM, volatile read and write operations are also not reordered with respect to operations on non-volatile variables.
...