unsafe.objectFieldOffset
调用unsafe.objectFieldOffset获取value字段在对象中的偏移量(其实就是一个字段到对象头部的偏移量,通过这个偏移量可以快速定位字段)
static { try { valueOffset = unsafe.objectFieldOffset(AtomicInteger.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); }}
定义value为volatile类型,保证value在多线程中的可见性
private volatile int value;
decrementAndGet
调用unsafe.getAndAddInt,参数为当前对象,偏移量,操作值
/** * Atomically decrements by one the current value. * * @return the updated value */public final int decrementAndGet() { //最后-1是由于getAndAddInt获取的值为交换前的值 return unsafe.getAndAddInt(this, valueOffset, -1) - 1;}
getAndAddInt
通过compareAndSwapInt返回循环getIntVolatile获取最新内存值
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;}
getIntVolatile
方法包含两个参数,当前对象,偏移量;获取内存地址指向的整数,并支持volatile语义
public native int getIntVolatile(Object var1, long var2);
compareAndSwapInt
方法包含了四个参数,当前对象,偏移量,期望值,新值;如果当前对象对应偏移量的值与期望值相同,则把当前对象的值更改为新值,并返回true;否则返回false
public final native boolean compareAndSwapInt(Object var1, long var2, int var4, int var5);