synchronized
andvolatile
Two keywords are often used in Java Concurrent Programming. We knowsynchronized
It can ensure that there will be no atomicity, visibility and ordering problems in concurrent programming, while volatile can only guarantee visibility and orderliness,Now that we have itsynchronized
Why do we need itvolatile
?
-
In order to solve the atomicity, visibility and orderliness in multithreading, Java provides a series of keywords related to concurrent processing, such as synchronized, volatile, final, concurrent packages, etc.
-
synchronized
By means of locking, it can be used as one of the solutions when atomicity, visibility and orderliness are needed. It seems to be “omnipotent”. Indeed, most concurrency control operations can be usedsynchronized
To complete. -
volatile
Through thevolatile
Variables are inserted into the memory barrier (JMM) of the JVM virtual machine before and after the operation, which ensures the visibility and order of variables in concurrent scenarios (implementation mechanism of operating system, assembly instructions)lock addl $0x0,(%rsp)
And cache consistency protocol (MESI). -
volatile
Keywords are not atomic, andsynchronized
Through JVM layer instructionsmonitorenter
andmonitorexit
Two instructions that can be guaranteed bysynchronized
The modified code can only be accessed by one thread at the same time, which can ensure that the CPU time slice will not appear and switch between multiple threads to ensure atomicity. -
synchronized
The implemented lock is essentially a blocking lock, that is, multiple threads are queued to access the same shared object. andvolatile
It is a lightweight synchronization mechanism provided by Java virtual machine. It is based on memory barrier. After all, he’s not a lock, so he won’t have itsynchronized
The problem of blocking and performance loss.
- In the general program, just addsynchronizedYou don’t need to add it
volatile
, but in singleton mode. It’s because ofPrevent instruction rearrangement。
be careful:
- This article emphasizes the instructions at the JVM level and those at the operating system level. Please do not confuse them.
-
In the operating system, two things happen to instructions with lock prefix in multi-core processor
2.1 write the data of the current processor cache line back to the system memory
2.2 this write back operation will invalidate the data in other CPU cache rows
This work adoptsCC agreementThe author and the link to this article must be indicated in the reprint