CAS ideas and principles to solve concurrency issues

 
Full name: Compare and swap (compare and exchange), a mechanism to solve the performance overhead caused by the use of locks under multithreading situation;
 
Principle thinking: CAS (V, A, B), V is a memory address, A is expected to original value, B is the new value. If the value V is equal to the memory address A, then the modified V B; otherwise, the description V processed by other threads. So, is it possible in the upcoming modification value V B when the other thread changes the value of the V? The answer is no, because the CAS operation is actually supported by a CPU, a primitive (primitives or computer network operating system language category. Is composed by a number of instructions for a process to complete certain functions, not having segmentation is performed, that is primitive must be continuous, not be interrupted during execution).
 

CAS disadvantages:

CAS although very efficient solution to the problem of atomic operations, but CAS is still three problems.
  1. Long cycle time overhead is large: if CAS fails, it will have to try. If the CAS for a long time has been unsuccessful, it might give a great deal of CPU overhead.
  2. Atomic operation can only guarantee a shared variable.
  3. ABA problem. If the value of the memory address V is the initial reading of A, and checks to its value at the time of preparation A still assignment, then we can say that the value is not changed other thread yet? If during this period its value had been changed to B, and later was changed back to A, CAS operation will mistakenly believe that it has never been changed. This vulnerability is called CAS operations "ABA" problem. Java and contract To solve this problem, provide a reference atomic class "AtomicStampedReference" with a marker, it can to ensure the correctness of CAS by controlling the value of the variable version. Therefore, before using CAS to consider carefully whether the "ABA" problem can affect programs concurrent validity, if the need to address the ABA problem, use the traditional mutual exclusion synchronization may be more efficient than the atomic class.

Guess you like

Origin www.cnblogs.com/zhaohuaxishi/p/12068209.html