Interpretation of the principle of volatile realization of visibility

In Java concurrent programming, the keywords volatile, synchronized and lock must not be bypassed. The volatile keyword is used to solve the visibility problem of shared variables (class member variables, class static member variables, etc.), not shared Variables (local variables of methods) are allocated in the stack of the JVM virtual machine, are private to the thread, and do not involve visibility issues. So what is visibility?
Visibility: This is defined in the JAVA specification: Java programming language allows threads to access shared variables. In order to ensure that shared variables can be updated accurately and consistently, threads should ensure that this variable is obtained separately through an exclusive lock. The popular method is that if there is a shared variable N, when two threads T1 and T2 obtain the value of N at the same time, T1 modifies the value of N, and T2 reads the value of N. Then the visibility specification requires that what T2 reads must be the modified value of T1, and T1 cannot be modified to the new value after T2 reads the old value. Shared variables modified by the volatile keyword can provide this visibility specification, which is also called read-write visibility. So the underlying implementation ensures that volatile variables are visible to read and write through mechanisms?
Volatile's implementation mechanism: Before talking about this problem, let's take a look at how the CPU executes java code.


First, after compilation, the Java code will be compiled into bytecode .class files, which will be loaded into the JVM at runtime. The JVM will convert the .class into specific CPU execution instructions, and the CPU loads these instructions one by one.

Guess you like

Origin blog.csdn.net/hongweideng/article/details/104453674
Recommended