java.util.concurrent.atomic.AtomicIntegerJava
文章发布较早,内容可能过时,阅读注意甄别。
# 1. 成员变量
static final Unsafe unsafe = Unsafe.getUnsafe()
设置unsafe.compareAndSwapInt更新,
// setup to use Unsafe.compareAndSwapInt for updates
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); }
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 2. 成员函数
getAndIncrement
方法的实现方式是:
public final int getAndAddInt(Object o, long offset, int delta) {
int v;
do {
v = getIntVolatile(o, offset);
} while (!compareAndSwapInt(o, offset, v, v + delta));
return v;
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
do{}while()循环中得到v返回,其中getIntVolatile
方法为native原生方法,
/** Volatile version of {@link #getInt(Object, long)} */
public native int getIntVolatile(Object o, long offset);
1
2
3
2
3
其中compareAndSwapInt
方法也为native原生方法,
/**
* 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);
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
加一时offset为1,减一时offset为-1。