AtomicInteger,由于存储的值的value是volatile类型所有具有线程可见性。通过CAS比较交换进行自增,或者更新值具有原子性。所以AtomicInteger是线程安全的具有类锁一样的线程安全性。
具体参见下面源码解析:
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 int value;//volatile保证了多线程之间的内存可见性
/**
* Creates a new AtomicInteger with the given initial value.
*
* @param initialValue the initial value
*/
public AtomicInteger(int initialValue) {
value = initialValue;
}
/**
* Creates a new AtomicInteger with initial value {@code 0}.
*/
public AtomicInteger() {
}
//expect预期原值,update更新值,如果预期值等于原值,用更新值替换原值。替换成功返回true,否则返回false.具有volatile的读写内存语义。
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
public final int decrementAndGet() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return next;
}
}