Basic concepts of atomicity, visibility, and order

The concepts of atomicity, visibility, and order are all based on multi-threaded operations.

 

 

Atomicity: An operation has an atomic operation, then we call it atomic. (What is an atomic operation? An operation is indivisible.)

        The atom is the smallest unit in the world and is indivisible . For example, a=0; (a is not long and double type) This operation is indivisible, so we say that this operation is an atomic operation. Another example: a++; this operation is actually a = a + 1; it is divisible, so it is not an atomic operation. Non-atomic operations will have thread safety issues, we need to use synchronization technology (sychronized) to make it an atomic operation. An operation is atomic, then we call it atomic. Some atomic classes are provided under the concurrent package of java. We can understand the usage of these atomic classes by reading the API. For example: AtomicInteger, AtomicLong, AtomicReference, etc.

  Synchronized in Java and operations in lock and unlock ensure atomicity.

 

Visibility:

  Visibility is a complex attribute, because errors in visibility always go against our intuition. Generally, we cannot ensure that the thread performing the read operation can see the value written by other threads in a timely manner, and sometimes it is even impossible. In order to ensure the visibility of memory write operations between multiple threads, a synchronization mechanism must be used.

  Visibility refers to the visibility between threads. The modified state of one thread is visible to another thread. That is, the result of a thread modification. Another thread can see it right away. For example: Variables modified with volatile will have visibility. Volatile modified variables do not allow thread internal caching and reordering, that is, directly modify memory. So it is visible to other threads. But there is a problem that needs to be noted here. Volatile can only make the content modified by him visible, but it cannot guarantee its atomicity. For example, volatile int a = 0; there is an operation a++ afterwards; this variable a is visible, but a++ is still a non-atomic operation, that is, this operation also has thread safety issues.

  Visibility is achieved in Java by volatile, synchronized and final.

 

Orderliness:

  The Java language provides two keywords, volatile and synchronized, to ensure the orderliness of operations between threads. Volatile is because it contains the semantics of "instruction reordering is prohibited". Synchronized is defined by "a variable only allows one at the same time. It is obtained by the rule that the thread performs a lock operation on it. This rule determines that two synchronized blocks holding the same object lock can only be executed serially.

 

Guess you like

Origin blog.csdn.net/chudelong1/article/details/108909206