在前面学习原子类的核心API过程中,CAS方法compareAndSet(int expect, int update)是每个原子类的核心方法,本文来深入这一核心算法底层的实现原理。
CAS底层原理(JDK1.8)
以AtomicInteger为例,我们分析下compareAndSet(int expect, int update)的源码。
/**
* 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);
}
该方法传入两个参数,当原子对象的当前值等于传入的期望值expect的时候,原子对象的值被设置为传入的更新值update,更新成功返回true,更新失败返回false,表示原子对象的当前值不等于传入的期望值expect。
其内部调用unsafe变量的compareAndSwapInt(this, valueOffset, expect, update)方法,那么问题来了?什么是unsafe,参数valueOffset又是什么?
认识Unsafe
我们发现,每个原子类里面都Unsafe类型的变量unsafe和long类型的变量valueOffset。
public class AtomicInteger extends Number implements java.io.Serializable {
private static final long serialVersionUID = 6214790243416807050L;
// 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); }
}
...
}
public class AtomicBoolean implements java.io.Serializable {
private static final long serialVersionUID = 4654671469794556979L;
// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
...
}
public class AtomicLong extends Number implements java.io.Serializable {
private static final long serialVersionUID = 1927816293512124184L;
// setup to use Unsafe.compareAndSwapLong for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
...

最低0.47元/天 解锁文章
935

被折叠的 条评论
为什么被折叠?



