JUC多线程及高并发-CAS-ABA

本文深入探讨了CAS(Compare-And-Swap)并发原语的工作原理及其在Java中的实现方式,包括Unsafe类的作用和原子变量类如AtomicInteger的使用。此外,还详细介绍了ABA问题及其解决方案,展示了如何利用AtomicStampedReference解决这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CAS是什么

CAS的全称为Compare-And-Swap,它是一条CPU并发原语。

它的功能是判断内存某个位置的值是否为预期值,如果是则更改为新的值,这个过程是原子的。

CAS并发原语体现在JAVA语言中就是sun.misc.Unsafe类中的各个方法。调用UnSafe 类中的CAS方法,JVM会 帮我们实现出CAS汇编指令。这是一种完全依赖于硬件的功能,通过它实现了原子操作。再次强调,由于CAS是一种系统原语,原语属于操作系统用语范畴,是由若干条指令组成的,用于完成某个功能的一个过程,并且原语的执行必须是连续的,在执行过程中不允许被中断,也就是说CAS是一”条CPU的原子指令,不会造成所谓的数据不一致问题。

例子

atomicInteger.compareAndSet 比较和设置值

package com.xin;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author :小心仔
 * @date :Created in 2021/11/2 21:30
 * @description:AtomicDemo
 * 
 *      compareAndSet 比较并交换
 */
public class AtomicDemo {

    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(5);

        System.out.println(atomicInteger.compareAndSet(5,2021) + "  --   atomicInteger.get:" + atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(5,2021) + "  --   atomicInteger.get:" + atomicInteger.get());
    }

}

在这里插入图片描述
底层 unsafe方法
在这里插入图片描述

Unsafe

是CAS的核心类,由于Java方法 无法直接访问底层系统,需要通过本地(native) 方法来访问,Unsafe相当于一 个后门, 基于该类可以直接操作特定内存的数据。Unsafe 类存在于sun.misc包中,其内部方法操作可以像C的指针一样 直接操作内存,因为Java中CAS操作的执行依赖于Unsafe类的方法。

注意Unsafe类中的所有方法都是native修饰的,也就是说Unsafe类中的方法都直接调用操作系统就层资源执行相应任务
在这里插入图片描述

CAS缺点

1、循环时间长开销比较大
2、只能保证一个共享变量的原子操作
3、引发ABA问题

ABA问题及解决

在这里插入图片描述

AtomicReference 原子引用例子

package com.xin;

import jdk.nashorn.internal.objects.annotations.Getter;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author :小心仔
 * @date :Created in 2021/11/3 20:17
 * @description:
 */
public class AtomicReferenceDemo {


    public static void main(String[] args) {

        AtomicReference<User>  atomicReference = new AtomicReference();

        User lisi = new User("lisi",20);
        User z3 = new User("z3",20);

        atomicReference.set(z3);

        System.out.println(atomicReference.compareAndSet(z3,lisi) + "\t" + atomicReference.get().toString());
        System.out.println(atomicReference.compareAndSet(z3,lisi) + "\t" + atomicReference.get().toString());
    }


}

class User {
    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

在这里插入图片描述

ABA问题演示及解决

package com.xin;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author :小心仔
 * @date :Created in 2021/11/3 20:38
 * @description:ABADemo
 */
public class ABADemo {

    public static void main(String[] args) {

        AtomicReference<Integer> atomicReference = new AtomicReference<>(100);

        // V initialRef 值, int initialStamp 版本号或时间戳
        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);

        System.out.println("=================以下是ABA问题产生=============");

        // 线程 t1 t2演示ABA问题
        new Thread(() -> {
            atomicReference.compareAndSet(100, 101);
            atomicReference.compareAndSet(101, 100);
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t1").start();

        new Thread(() -> {
            atomicReference.compareAndSet(100, 2021);
            System.out.println(Thread.currentThread().getName() + "\t 最后值:" + atomicReference.get().toString());
        }, "t2").start();

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("=================以下是ABA问题解决=============");

        // 线程 t3 t4解决ABA问题
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            atomicStampedReference.compareAndSet(100, 101, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println("第二次版本号:" + atomicStampedReference.getStamp());
            atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println("第三次版本号:" + atomicStampedReference.getStamp());
        }, "t3").start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println("第一次版本号:" + stamp);
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第四次版本号:" + atomicStampedReference.getStamp());
            atomicStampedReference.compareAndSet(100, 2021, stamp, atomicStampedReference.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "\t 最后值:" + atomicStampedReference.getReference());
        }, "t4").start();

    }

}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小心仔

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

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

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

打赏作者

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

抵扣说明:

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

余额充值