Difference between synchronized and volatile (visibility vs prohibiting instruction reordering)?

volatile, final, synchronized can achieve visibility

The first is that the essence of volatile is to tell the JVM that the value of the current variable in the register is uncertain and needs to be read from main memory. And synchronized locks the current variable, only the current thread can access the variable, other threads are blocked.

Then volatile can only be used at the variable level, and synchronized can be used in variables and methods.

The third point is that volatile can only achieve the modification visibility of variables, but does not have atomic characteristics, while synchronized can guarantee the modification visibility and atomicity of variables.

The fourth difference is that volatile will not cause thread blocking, while synchronized may cause thread blocking.

Finally, variables marked with volatile will not be optimized by the compiler, while variables marked with synchronized can be optimized by the compiler.

Conditions to be met when using volatile: 1. The operation result does not depend on the current value of the variable, or it is guaranteed that only one thread modifies the value of the variable.

2. No need to participate in invariant constraints with other state variables

3. No need to lock when accessing variables

Immutability of volatile:

1. The data of the current processor cache line will be written back to the system memory

2. This write-back operation will invalidate the data cached at the memory address in other CPUs.

A volatile variable will have a lock add instruction after assignment. This instruction is equivalent to a memory barrier. When reordering, the instructions after the barrier cannot be reordered before the barrier.

Volatile prohibits instruction reordering: ordinary variables only guarantee that the correct results can be obtained in all places that depend on the assignment results during the execution of the method, and cannot guarantee that the order of variable assignment operations is consistent with the execution order in the program code.

Volatile guarantees visibility: the add instruction will invalidate the data cached in the working memory of other worker threads.

Guess you like

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