并发编程原理与实战(三十一)从原子类到CPU原子指令,CAS实现全链路拆解

在前面学习原子类的核心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;
    ...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

帧栈

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值