CAS is a CPU instruction, get it! Don't understand? Then come in and have a look!

Hello everyone, I am, 方圆
we must learn many threads


1. Tell me, what is CAS?

Insert picture description here
No, you want to hear it.

CAS Chinese name “比较并交换”, it CPU指令can not be interrupted, but also our common 乐观锁realization of the principle, CAS in three operands, respectively 内存值, 预期值and should 修改的值, if and only if the same memory value and the expected value, will be Modify it, otherwise do not modify.

1.1 Now let's write a demo of CAS principle by ourselves

Insert picture description here
If you understand it, you will love to learn, then watch

public class Demo {
    
    
	//内存值
    private volatile int value;
    //期望值和修改后的值都有了,这个方法用synchronized修饰
    public synchronized void compareAndSwap(int expectedValue, int newValue){
    
    
        if(expectedValue == value)
            value = newValue;
    }
}

2. Analyze the source code of AtomicInteger

Insert picture description here
Insert picture description here

2.1 Let's focus on the getAndIncrement method

Operation is 当前对象, value的地址值,增加值为1

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

Among them, the getAndAddInt method uses the spin of CAS.
Insert picture description here
The getiIntVolatile method is a c++ method modified by native
Insert picture description here

  • To sum up,
    AtomicInteger loads the Unsafe tool, which is used to directly manipulate 内存data.
    Use volatile to modify fields to ensure visibility

3. Briefly talk about the Unsafe class

  • Unsafe is the core class of CAS, Java cannot directly access the underlying operating system, but access through nativemodified methods
  • valueOffset represents the offset address of the variable value in the memory, because Unsafe obtains the original value of the data according to the memory offset address, so that we can implement CAS through Unsafe

Getting started

Guess you like

Origin blog.csdn.net/qq_46225886/article/details/107883418