volatileTwo keywords are often used in Java Concurrent Programming. We know
synchronizedIt 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 it
synchronizedWhy do we need it
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.
synchronizedBy 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 used
volatileVariables 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).
volatileKeywords are not atomic, and
synchronizedThrough JVM layer instructions
monitorexitTwo instructions that can be guaranteed by
synchronizedThe 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.
synchronizedThe implemented lock is essentially a blocking lock, that is, multiple threads are queued to access the same shared object. and
volatileIt 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 it
synchronizedThe 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。
- 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