AtomicInteger
自增1并获取之前值
/**
* Atomically increments by one the current value.
*
* @return the previous value
*/
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
自增1并获取更新后值
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
valueOffset 是 AtomicInteger 保存值的变量,在class中的Offset,Unsafe类中会用到
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
##保存操作值的变量
private volatile int value;
Unsafe::getAndAddInt 源码
/**
* Atomically adds the given value to the current value of a field
* or array element within the given object <code>o</code>
* at the given <code>offset</code>.
*
* @param o object/array to update the field/element in
* @param offset field/element offset
* @param delta the value to add
* @return the previous value
* @since 1.8
*/
public final int getAndAddInt(Object o, long offset, int delta) {
int v;
do {
//获取对象中对应属性的值
v = getIntVolatile(o, offset);
//这行是关键,调用处理器硬件指令,这个操作是原子的
//v是期望值,v + delta是准备设置的新值
//如果此时未有其实线程更改v则返回成功,否则失败
} while (!compareAndSwapInt(o, offset, v, v + delta));
return v;
}
Unsafe::compareAndSwapInt
/**
* Atomically update Java variable to <tt>x</tt> if it is currently
* holding <tt>expected</tt>.
* @return <tt>true</tt> if successful
*/
public final native boolean compareAndSwapInt(Object o, long offset,
int expected,
int x);