What is CAS in Java?

  1. CAS, compareAndSwap, compare and replace

  2. In Java, the following is a partial implementation of the AtomicInteger class, as well as the other Atomic classes

    public final int getAndIncrement() { return unsafe.getAndAddInt(this, valueOffset, 1); }

Broadening calls getAndAddInt to the sun.misc.Unsafe class

Public final int getAndAddInt(Object o, long offset, int delta) {int v; do { v = getIntVolatile(o, offset); } while (! compareAndSwapInt(o, offset, v, v + delta)); // return v; }Copy the code

CompareAndSwapInt is a native method, which I won’t go into here. The code flow chart above looks like this

As you can see, is the constant in a while with the current values in the memory, and then calculated, and then again in comparison with the values of the values in the memory and before get, if the same as the default has not been modified, other threads updated to the new value result, if not the same, show the value is modified in memory, to do it again. This is called spin.

Disadvantages:
  1. When multiple threads are in contention, they may spin all the time, consuming CPU
  2. ABA problem: A->B->A, in the figure 1 to 3, the value is changed from A to B, and then changed to A, when the execution of 3 will judge that the value has not changed, in fact, has changed, the basic type may not affect, because there are multiple variables, it is more difficult. Solution add an operation version number, for example, AtomicStampedReference