private static final Unsafe unsafe = Unsafe.getUnsafe();
// value字段的偏移量
private static final long valueOffset;
static {
try {
//获取value字段的偏移量
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
//volatile修饰value从而保证value值的线程可见性
private volatile int value;
public AtomicInteger(int initialValue) {
value = initialValue;
}
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
//Unsafe源码
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
//通过字段的内存地址获取最新的值
var5 = this.getIntVolatile(var1, var2);
//CAS更新新值,如果失败重试
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
}
var1
,var2
联合定位字段的内存地址
compareAndSwapInt
是CAS操作更新新值,当compareAndSwapInt
失败,do代码块会再次执行,获取最新的值var5,然后重新执行compareAndSwapInt
,直至成功为止.
网友评论