The second semantic of volatile variables is to disable instruction reordering optimizations

Especially in the case of multiple CPUs, the volatile keyword should be given priority when concurrency. The program can be executed according to the sequential order of the code. Otherwise, the code written later may be executed first. Because the JVM may reorder the execution of the code, the reordering is to improve the efficiency of program execution. However, when it is concurrent, it is prone to problems.

The second semantics of using volatile variables is to prohibit instruction reordering optimization. Ordinary variables only ensure that the correct results can be obtained in all places that depend on the assignment results during the execution of the method, but cannot guarantee the order of variable assignment operations. Consistent with the execution order in the program code. Because this is not perceptible during the execution of a thread's method, this is the so-called "Within-Thread As-If-Serial Semantics" described in the Java Memory Model.

"In-depth understanding of JVM virtual machine"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325520991&siteId=291194637