CAS summary

A: CAS (Compare-and-Swap), that is, compare and replacement, is a technique often used to achieve concurrent algorithms, Java and many classes in the contract are used CAS technology.
CAS is an abbreviation of the English word CompareAndSwap, Chinese meaning is: compare and replace. CAS requires three operands: a memory address V, the expected value of the old A, is about to be updated target B.
When the CAS instruction is executed, if and only if the memory address of the value of the expected value of V A is equal to the value of V memory address changed to B, otherwise it does nothing. Compare and replace the entire operation is an atomic operation.
CAS is to get the data through an infinite loop, Ruoguo cycle in the first round, a thread gets inside the address value is modified b-threaded, then a thread needs to spin cycle to the next possible opportunity to perform.
 
 
Two: CAS disadvantages:
1: long cycle time much overhead:
We can see that when getAndAddInt method of execution, if the 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:
When performing operations on a shared variable, we can use the CAS cycle approach to ensure an atomic operation, but when multiple shared variables operating cycle CAS can not guarantee atomic operations, this time we can use locks to ensure atomicity .
 
 
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 in order to solve this problem,
Providing atom marked with a reference to the class "AtomicStampedReference", which can be controlled by a variable value later to ensure the correctness of CAS.
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.
 
Three: CAS is an optimistic lock, there are many classes is to ensure atomic JUC below in order to solve concurrency issues. The main use category are: Lock, AtomicInteger etc.
 
 

Guess you like

Origin www.cnblogs.com/jelly12345/p/11938423.html