Three core multi-threaded Java: atomicity, visibility, sequential

! ! ! The volatile keyword can only guarantee the visibility of the order, we can not guarantee atomicity.

Atomicity

Java and atomicity on database transaction atomicity almost one operation executed either all succeed or fail.

JMM only to ensure the basic atomic, but similar operation i ++ or the like, appears to be an atomic operation, which in fact relate to:

  • Gets the value of i.
  • Increment.
  • Re-assigned to i.
    ( Think a few steps which will operate as an atomic steps which will be synchronized with the overall process and the lock can be used as an atomic operation )
    This three-step operation, so I want to achieve i ++ atomic operations so you need to use synchronized or lock to be locked. deal with.
    If self-energizing operation of the base class can be used AtomicInteger class to implement such atoms
    (which is essentially a CPU use level of CAS (Compare and Swap, and then compare i.e. exchange) instruction to complete).

Visibility

In modern computers, since the CPU is not high efficiency of data read directly from main memory, the corresponding CPU will cache, main memory data is first read into the cache, after the first update thread to modify the data cache, then will be updated to the main memory. If at this time has not yet updated data to another thread to read data from main memory at this time it is before the modification.

The volatile keyword is used to ensure the visibility of memory, when the thread A renewed volatile variables, it will be immediately flushed to the main thread, and the value of the variable empty the rest of the cache, causing the rest of the thread can only go to the main memory read take the latest value.

Variables volatile keyword using modified to read each will get the latest data, regardless of which thread of this variable changes will be immediately flushed to main memory.

synchronized and can be locked to ensure the visibility of the realization of the principle is, before the release of the remaining thread lock is not access the shared variable. But compared to volatile and large overhead.

Sequential

Sometimes In order to improve the overall efficiency of JVM instructions will cause rearrangement can be executed sequentially. But the JVM can not be anything rearrangement, it is possible to ensure that the rearrangement case of performing consistent with the results of the final results and code sequence.

Rearrangements in a single thread no problem, but data inconsistencies occur in multiple threads.

Refer to the original: https: //github.com/crossoverJie/JCSprout/blob/master/MD/Threadcore.md

Published 28 original articles · won praise 24 · views 10000 +

Guess you like

Origin blog.csdn.net/XM_no_homework/article/details/103890399