introduce

CAS: Compare and Swap. For concurrency, locking is a pessimistic strategy that blocks thread execution. Technology naturally craves optimistic strategies, and locklessness is a conceptual embodiment. One technical support for lock-free is CAS.

reading

All the uses of CAS I’ve seen so far are supported through the Unsafe class. CAS has three operands V (memory value, the true shared memory value, not in the cache), A (expected or cached value), and B (modified new value). We use AtomicInteger’s compareAndSet method to give us a concrete understanding of the three operands (the core is to understand the three operands).

compareAndSet

public final boolean compareAndSet(int expect, Int the update) {/ / U is Unsafe class / / private static final sun. Misc. Unsafe U = sun. Misc. Unsafe. GetUnsafe ();return U.compareAndSwapInt(this, VALUE, expect, update);
    }
Copy the code

The Unsafe class’s implementation of compareAndSwapInt is native, which is the C++ implementation. It’s an atomic operation. Its atomicity is achieved through the CAS atomic instruction, guaranteed by the processor. If you want to learn more, click here

  • VALUE is V in the CAS. How did he get it?
Static {try {// The Unsafe class also provides methods. Cooperate with the reflection to the value the values in the Field, the corresponding real memory value = u.o. bjectFieldOffset (AtomicInteger. Class. GetDeclaredField ("value")); } catch (ReflectiveOperationException e) { throw new Error(e); }}Copy the code
  • Expect is A in CAS
Private volatile int value; // volatile int value; // Use this method to get value public final intget() {
        return value;
    }
Copy the code
  • Update, or B in CAS, is usually computed using functions provided in the form of functional programming
public final int getAndUpdate(IntUnaryOperator updateFunction) {
        int prev, next;
        do {
            prev = get();
            next = updateFunction.applyAsInt(prev);
        } while(! compareAndSet(prev, next)); // Note the loop condition, the CAS operation fails to control the attempt to continuereturn prev;
    }
Copy the code

I believe that by now, we have a general impression of CAS. So much for this article