Hello everyone, I am,
方圆
we must learn many threads
table of Contents
1. Tell me, what is CAS?
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
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
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.
The getiIntVolatile method is a c++ method modified by native
- 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
native
modified 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