java-cas

CAS: CAS What is the mechanism?
cas aim is to achieve an atomic operation to explain:
"atomic operations (atomic operation) is not required synchronized", which is a multi-threaded programming commonplace. Refers to the so-called atomic operations will not be interrupted thread scheduling mechanism operation; this operation once started, has been run to the end, without any intermediate context switch (cut [1] change to another thread). This is Baidu Encyclopedia explanation
means that the state will not be interrupted by intermediate states, such as bank transfer mechanism, an account of deducting money, money account is also necessary to collect the money, it can not be interrupted
operations in java Atoms for multithreading operational scenario to avoid a shared variable did not meet expectations

See an example of unsafe scenario:

  

This result is not necessarily count 200, because there multithreaded competition may be less than 200, if the run method of the synchronized code block inside with the operation state of each thread is not affected by the influence of other threads, to achieve the atomic operation, most of the result will be 200.  

A series of lower-atomic java.util.concurrent.atomic package

 

This last operation is 200, because the atomic class specifically address this problem

Atoms class value by using the value of the shared variable volatile achieved.

The core principle is: CAS mechanism which uses three basic operand: memory address V, the expected value of the old A, to modify the new value of B.

Each update when compared with the old value should be the value memory, inconsistencies will update fails, then continue to update the value of the use of memory (there have been spin-operate in a highly concurrent dangerous cpu resources will be severely depleted)

Such as a second thread 97 runs to the first thread when it is running due to a slow response when 5 5 then increment the memory will fail inconsistent value and the old value, so that the spin is performed from the beginning 97 to 98, the first two thread starts running 98 old value is 97 so 98 will fail to start spinning, and so on to achieve the end result is alternately increment 200.

参见:https://ss.csdn.net/p?https://mmbiz.qpic.cn/mmbiz_jpg/NtO5sialJZGpfMM4tNG7D3k05o337rpShibke60ZSQ8jQuoQMdXK7fcyLkkDGS2EfOiahzQQS9DPHmjsXcB8ibWKdg/0?wx_fmt=jpeg

图文并茂的讲解。

cas是乐观锁,synchronized 是悲观锁,  在大并发下synchronized 的使用要比cas好些

 

Guess you like

Origin www.cnblogs.com/ljy-skill/p/11069761.html