学习笔记(14):Java并发编程精讲-乐观锁CAS实现及应用

立即学习:https://edu.csdn.net/course/play/26270/326874?utm_source=blogtoedu

一、乐观锁和悲观锁的区别

 

二、CAS 乐观锁

  • CAS 解释

全名:compare and swap,先比较后设置,CAS 是一个原子操作

  • 适用场景

更新一个值,不依赖于加锁实现,可以接受CAS失败

  • 局限

只可以更新一个值,如AtomicReference、AtomicInteger需要同时更新时,无法做到原子性。

从源码中分析:expect为原来的值,update为更新的值。如果程序要将 1 改为 2。则只有 expect =1时,才能成功把值update为2。

AtomicInteger 类中的 compareAndSwapInt 方法是 native 方法,是调用 JNI 的方法,底层其实就是通过一个CPU指令完成。

 

三、CAS 的自旋问题

如果CAS不成功,则会不停循环,原地自旋,长时间自旋自然会给CPU带来非常大的开销。

 

四、ABA 问题

线程1 : 将 value A->B

线程2 : 将 value A->C

但是在整个时间线上,虽然最终线程2能够将 A->C,但是线程2不知道中间 value 是变更过的。

 

五、AtomicStampedReference 如何处理 ABA 问题

public class AtomicStampedReference<V> {

    private static class Pair<T> {
        final T reference; // 当前属性的值
        final int stamp; // 时间戳
        private Pair(T reference, int stamp) {
            this.reference = reference;
            this.stamp = stamp;
        }
        static <T> Pair<T> of(T reference, int stamp) {
            return new Pair<T>(reference, stamp);
        }
    }

...

/**
     * Atomically sets the value of both the reference and stamp
     * to the given update values if the
     * current reference is {@code ==} to the expected reference
     * and the current stamp is equal to the expected stamp.
     *
     * @param expectedReference the expected value of the reference
     * @param newReference the new value for the reference
     * @param expectedStamp the expected value of the stamp
     * @param newStamp the new value for the stamp
     * @return {@code true} if successful
     */
    public boolean compareAndSet(V   expectedReference,
                                 V   newReference,
                                 int expectedStamp, // 期望的时间戳
                                 int newStamp // 新的时间戳) {
        Pair<V> current = pair;
        return
            expectedReference == current.reference &&  // 只有当期望的时间戳和当前value记录的时间戳一致,才允许更新
            expectedStamp == current.stamp &&
            ((newReference == current.reference &&
              newStamp == current.stamp) ||
             casPair(current, Pair.of(newReference, newStamp)));
    }

...

}

引入 timestamp ,记录对象当前时间戳。记录期望更改value时的时间戳,和当前 value 的时间戳进行对比,只有相等才能够进行更新。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Charlven

你的鼓励将是我最大的动力哦

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

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

打赏作者

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

抵扣说明:

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

余额充值