A simple understanding of the CAS algorithm

When understanding and looking at the source code of AbstractQueuedSynchronizer, compareAndSetHead and compareAndSetTail often appear. The bottom layer of these two methods calls unsafe.compareAndSwapObject ( this , value Offset , expect, update);

This method mainly uses the CAS instruction of the CPU, that is, the CAS algorithm.

 

The main logic of the method is

if (this == expect) {
  this = update
 return true;
} else {
return false;

In this way we can understand CAS as:

CAS has 3 parameter values, the memory value V(this) , the old value A(expect) and the new value B(update) . Modify memory value V to B if and only if expected value A and memory value V are the same , otherwise do nothing.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325765439&siteId=291194637