A.什么是CAS?
<1>全称是compareAndSet,含义是比较并交换。
<2>CAS有3个操作数,内存值V,旧的预期值A,要修改的新值B。当且仅当预期值A和内存值V相同时,将内存值V修改为B,否则返回V
B.下面来看下AtomicInteger.incrementAndGet()的源码
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
private volatile int value;
public final int get() {
return value;
}
public final boolean compareAndSet(int expect,int update)
{
return unsafe.compareAndSwapInt(this.valueOff,expect,update);
}
可以看到源码中的for循环本质就是while(true),只有当满足if条件时才会返回并跳出while(true)循环,这个循环有一个专有名词就是自旋
<1>.如何保证get()方法返回的是内存中最新值?value被volatile修饰,volatile保证了可见性,自然是最新值
<2>.可以看出compareAndSet方法底层调用的是compareAndSwapInt(),compareAndSwapInt()的运行过程又是怎样的呢?/compareAndSet方法是如何保证原子性操作的?
(1)通过this+valueOff获取当前主存中的最新值
(2)将最新值和expect进行比较,如果而知值相等,将this+valueoff对应的值修改为update,并返回true,如果不等则返回false
这样就会发现,只有当compareAndSet方法中的get()当前读到的值和主存中的实际值相等时才可以修改,这样就保障了原子性。