众所周知int i++不能保证原子操作,多线程时推荐使用AtomicInteger.getAndIncrement().那么AtomicInteger是如何保证线程安全的呢?

看源码:

public class AtomicInteger extends Number implements java.io.Serializable {
// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
// 省略...N行
private volatile int value; // ①
/**
* Atomically increments by one the current value.
*
* @return the previous value
*/
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update); // ②
}
}

① volatile 关键字保证了多线程value 的可见性和共享性。

② unsafe.compareAndSwapInt方法基于native方法(硬件层面保证)保证原子性