CAS operations can be divided into the following three steps:
Step 1. Read the old value (that is, the value of the variable to be read from system memory, for example: reading the value of the variable i)
Step 2. Novelty value (that is, the value read from memory operation, but the operation does not modify the value of the variable in memory, such as: i=i+1, this step is only i+1, no assignment, do not modify the memory i)
Step 3. Two indivisible atomic operations
Step One: compare the current value of the variable in memory with the same old value that was first read (that is, to reread the value of I from memory, compared to the first read i)
Step Two: if the values are the same, the new value to be evaluated is written in memory (i.e.: i=i+1, changing the value of I in memory)
If the two values are not the same, repeat step 1 to start
Note: These two operations are indivisible atomic operations and must be done both at the same time
CAS Operations
CAS is the abbreviation for the word compare and set, which means that the value is not changed before set, and is assigned only if it is unchanged.
We do this a lot.
[Java] view plain copy print? if (a==b) {a++; Imagine what to do if the value of a is changed before you do a++. a++ also execute it. This problem occurs because in a multithreaded environment, the value of a is in an indeterminate state. The use of locks can solve such problems, but CAs can also be resolved without locking.
[Java] view plain copy print? int expect = A; if (A.compareandset (expect,a+1)) {doSomeThing1 (); else {doSomeThing2 (); So if the value of a is changed, a++ will not be executed.
According to the above, after A!=expect, a++ will not be executed, if we still want to perform a++ operation, it does not matter, you can use while loop
[Java] view plain copy print? while (true) {int expect = A; if (A.compareandset (expect, A + 1)) {doSomeThing1 (); Return else {doSomeThing2 (); } }
Using the above method, the a++ operation is implemented without the lock, which is actually a non-blocking algorithm.
Application
Most of the classes in the Java.util.concurrent.atomic package employ CAS operations, taking Atomicinteger as an example to see how several of its main methods are implemented:
[Java] View plain copy print Public final int getandset (int newvalue ) { for (;;) { int current = get (); if (Compareandset (current, newvalue)) return current; } } Getandset method The interpretation in the JDK documentation is that it is set to the given value in atomic form and the old value is returned. Where the atom is represented, it's on the Compareandset, and see how Compareandset is implemented: [Java] View plain copy print? Public final boolean compareandset (int expect, int update) { return unsafe.compareandswapint (This, valueoffset, expect, update) ; } As expected, it is the unsafe class of the CAS operation completed.
Let's look at how the a++ operation is implemented:
[Java]