CAS 底层实现
AtomicInteger 为例
- 利用
unsafe
工具拿到value
的内存地址 - 并且利用
volatile
保证value
的可见性 ```java private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static { try { valueOffset = unsafe.objectFieldOffset (AtomicInteger.class.getDeclaredField(“value”)); } catch (Exception ex) { throw new Error(ex); } }
private volatile long value;
```java
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
Unsafe
这里的
getAndAddInt
就是 do while + cms// class Unsafe
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
var5 = this.getIntVolatile(var1, var2);
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
}
cms 是 native 方法,由 os 保证原子性
public final native boolean compareAndSwapInt(Object var1, long var2, int var4, int var5);