Since synchronized is omnipotent, why volatile is needed?

Time:2020-11-23

synchronizedandvolatileTwo keywords are often used in Java Concurrent Programming. We knowsynchronizedIt 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 itsynchronizedWhy do we need itvolatile

  1. 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.

  2. 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 usedsynchronizedTo complete.

  3. volatileThrough thevolatileVariables 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).

  4. volatileKeywords are not atomic, andsynchronizedThrough JVM layer instructionsmonitorenterandmonitorexitTwo instructions that can be guaranteed bysynchronizedThe 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.

  5. synchronizedThe implemented lock is essentially a blocking lock, that is, multiple threads are queued to access the same shared object. andvolatileIt 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 itsynchronizedThe problem of blocking and performance loss.

  1. In the general program, just addsynchronizedYou don’t need to add itvolatile, but in singleton mode. It’s because ofPrevent instruction rearrangement

be careful:

  1. This article emphasizes the instructions at the JVM level and those at the operating system level. Please do not confuse them.
  2. 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


jzhao