Compare And Swap(Set)

cas(V,Expected,NewValue)
    if  V == Expected
        V = NewValue
    otherwise 
        try again or fail 
Copy the code

CAS is a CPU concurrency primitive whose function is to determine whether a value at a location in memory is the expected value and, if so, to change to the new value. This process is atomic

The CAS concurrency primitive is implemented in the Java language as the various methods of the Sun.misc. Unsafe class. Calling the Unsafe class method, the Jvm implements the CAS assembly directive for us.

CAS is a completely hardware-dependent function that implements atomic operations through hardware.

A primitive belongs to the category of operating system language, which consists of several instructions and is used to complete a process of a certain function. The execution process of the primitive must be continuous and cannot be interrupted in the execution process. That is, CAS as a concurrency primitive is an atomic instruction and does not cause data inconsistency problems.

Analyze the AtomicInteger class -> getAndIncrement() method

  • unsafe.getAndAddInt(this, valueoffset, 1)

  • Valueoffset: memory offset and address of the value variable

  • Unsafe class -> getAndAddInt(Object var1, Long var2, int var4)

    Var1 AtomicInteger The memory offset of the value variable of the AtomicInteger object referenced var2 AtomicInteger Var4 The value to be increased (1) VAR5 The memory offset from the object reference and the value variable of the object The latest value of the value variable from main memory to working memory is assigned to var5

    The value of the copy of the value variable in the thread working memory is compared with var5 if the same is written back to the main memory value is: Var5 + var4 returns true if different continue loop {take the latest value -> value variable in the thread working memory copy of the value compared to var5 until the update is complete end loop}

  • unsafe.cpp -> atomic::cmpxchg

  • atomic_linux_x86.inline.hpp

  • Lock + CMPXCHG 2 hardware instructions to achieve atomicity

  • Lock Cache row lock/bus lock

What is the Unsafe class

The Unsafe class exists in the Sun.misc package, and its internal methods can manipulate memory as directly as Pointers to C

Since Java methods cannot access the underlying system directly and need to be accessed through native methods, Unsafe is a backdoor for manipulating memory-specific data.

Unsafe is the core CAS class, and CAS operations in Java are implemented using the Unsafe class.

All methods in the Unsafe class are native, meaning that all methods in the Unsafe class call directly on the underlying operating system resources to perform tasks

In the case of AtomicInteger, Unsafe addresses the value variable in main memory via its memory offset and then performs the CAS operation.