Chapter 3rd: Sharing of objects
- The understanding of the volatile keyword
a volatile variable that is used to ensure that a variable's row action is notified to other threads. When a variable is declared as a volatile type, the compiler and the runtime will notice that the variable is shared, so the operation on that variable is not reordered with other memory operations. Volatile variables are not cached to registers or other processors where they are not visible, so the most recent write value is always returned when reading a variable of type volatile. The volatile keyword can be understood as a weak synchronization mechanism for Java (compared to synchronized). Volatile also guarantees the atomicity of 64-bit read/write operations. It is much more expensive to read volatile variables at the same time (not without an intuitive impression).
- The difference between the locking mechanism (synchronized) and the volatile
The locking mechanism ensures that both visibility and atomicity are guaranteed, but volatile variables ensure visibility only.
- Conditions for using volatile variables
The write to the variable does not depend on the current value of the variable (volatile does not guarantee the atomicity of the operation on that variable).
The variable is not included in the invariant condition.
No lock is required when accessing variables.
Volatile variable understanding via "Java Concurrency Programming Combat"