The use of the volatile keyword in Java involves the Java memory model, JMM. Simply put, each thread has a local memory (virtual), and the thread-shared variables are stored in main memory, and the heap is present in the master. The memory access method is as shown.
The effect of volatile is summarized as follows:
(1) Visibility: Reading a volatile variable will always be able to see (any thread) the last write to the variable, which is able to read the most recent value.
(2) Atomicity: Read/write C operations for Vloatile variables are atomic, but composite operations are not atomic.
The operation procedure described in the above diagram
(1) Thread A writes: The value of n is updated in thread A, the value of flag, the update to n is only in local memory, but after the flag is written, flag is volatile, causing the two shared variables in local memory A to be updated by thread A to be flushed into main memory. This ensures that the most recent write value of the volatile variable is kept in main memory.
(2) thread B reads: When thread B reads a variable of type volatile, JMM will place the local memory as invalid, and the thread will then read the shared variable from main memory. This guarantees that the most recent value in main memory is read.
Java vloatile Keywords