并发编程之CAS&Atomic原子操作

目录

什么是CAS?

CAS 原子操作的三大问题

ABA问题

循环时间长开销大

只能保证一个共享变量的原子操作

jdk中的原子操作类

AtomicInteger

AtomicLong

AtomicReference

LongAdder


什么是CAS?

        CAS是“比较并交换”(Compare and Swap)的缩写。CAS是一种多线程同步的技术,用于实现多线程环境下的原子操作,常用于实现无锁的数据结构和线程安全算法。

        CAS 操作过程都包含三个运算符:一个内存地址 V,一个期望的值 A 和一 个新值 B,操作的时候如果这个地址上存放的值等于这个期望的值 A,则将地址 上的值赋为新值 B,否则不做任何操作。

        CAS 的基本思路就是,如果这个地址上的值和期望的值相等,则给其赋予新 值,否则不做任何事儿,但是要返回原值是多少。自然 CAS 操作执行完成时,在 业务上不一定完成了,这个时候我们就会对 CAS 操作进行反复重试,于是就有了 循环 CAS。很明显,循环 CAS 就是在一个循环里不断的做 cas 操作,直到成功为 止。Java 中的 Atomic 系列的原子操作类的实现则是利用了循环 CAS 来实现。

CAS 原子操作的三大问题

ABA问题

        ABA问题是指在多线程环境下,一个值由A变为B,再由B变回A,这时如果仅使用CAS来判断值是否变化,可能无法正确地捕捉到中间的变化,从而导致不正确的结果。ABA问题包含以下步骤:

1. 初始时,某共享变量的值为A。

2. 线程1读取该共享变量的值为A,然后线程1被阻塞或者挂起。

3. 线程2将该共享变量的值由A改为B,再改回A。

4. 线程1恢复执行,使用CAS检查共享变量的值是否仍然为A,由于共享变量的值此时确实为A,CAS操作成功。

在以上过程中,线程1没有察觉到共享变量B发生过变化,因为CAS只检查共享变量的当前值和预期值是否相等。

解决ABA问题,可以使用带有版本号的变量,也被称为版本号引用。比如使用Atomic包下工具类AtomicStampedReference:

import java.util.concurrent.atomic.AtomicStampedReference;

public class ABATest {
    public static void main(String[] args) {
        // 初始值为A,初始版本号为0
        AtomicStampedReference<String> atomicRef = new AtomicStampedReference<>("A", 0);

        // 线程1读取当前值和版本号
        int[] stampHolder = new int[1];
        String value1 = atomicRef.get(stampHolder);

        // 线程2修改值为B,并增加版本号
        atomicRef.compareAndSet(value1, "B", stampHolder[0], stampHolder[0] + 1);

        // 线程1再次尝试CAS,但由于版本号已经变化,不再匹配,不会发生CAS成功
        boolean success = atomicRef.compareAndSet("A", "C", stampHolder[0], stampHolder[0] + 1);

        System.out.println("CAS success: " + success);  // 输出false,表示CAS操作失败
    }
}
循环时间长开销大

       自旋 CAS 如果长时间不成功,会给 CPU 带来非常大的执行开销。

只能保证一个共享变量的原子操作

        当对一个共享变量执行操作时,我们可以使用循环 CAS 的方式来保证原子操 作,但是对多个共享变量操作时,循环CAS就无法保证操作的原子性,这个时候就可以用锁来完成操作。


jdk中的原子操作类

AtomicInteger

get():获取当前值。

set(int newValue):设置为给定值。

getAndIncrement():获取当前值并递增。

compareAndSet(int expect, int update):比较当前值是否等于预期值,若相等则更新为新值。

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerExample {
    private static AtomicInteger counter = new AtomicInteger(0);

    public static void main(String[] args) {
        System.out.println("Initial value: " + counter.get());

        int newValue = 10;
        counter.set(newValue);
        System.out.println("Set new value: " + counter.get());

        int oldValue = counter.getAndIncrement();
        System.out.println("Old value: " + oldValue + ", After increment: " + counter.get());

        int expectedValue = 10;
        int updateValue = 20;
        boolean updated = counter.compareAndSet(expectedValue, updateValue);
        System.out.println("Value updated? " + updated + ", Current value: " + counter.get());
    }
}
AtomicLong

get():获取当前值。

incrementAndGet():递增并获取新值。

getAndSet(long newValue):设置为给定值,并返回旧值。

import java.util.concurrent.atomic.AtomicLong;

public class AtomicLongExample {
    private static AtomicLong counter = new AtomicLong(0);

    public static void main(String[] args) {
        System.out.println("Initial value: " + counter.get());

        long newValue = 10;
        counter.set(newValue);
        System.out.println("Set new value: " + counter.get());

        long incrementedValue = counter.incrementAndGet();
        System.out.println("Incremented value: " + incrementedValue);

        long oldValue = counter.getAndSet(20);
        System.out.println("Old value: " + oldValue + ", Current value: " + counter.get());
    }
}
AtomicReference

get():获取当前引用对象。

set(V newValue):设置为给定值。

compareAndSet(V expect, V update):比较当前引用对象是否等于预期值,若相等则更新为新值。

import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceExample {

    public static void main(String[] args) {
        // 初始值为 "Hello"
        AtomicReference<String> atomicReference = new AtomicReference<>("Hello");

        // 获取当前值
        String currentValue = atomicReference.get();
        System.out.println("Current Value: " + currentValue);

        // 尝试更新值,如果当前值是 "Hello",则更新为 "World"
        boolean updated = atomicReference.compareAndSet("Hello", "World");
        System.out.println("Updated: " + updated);

        // 获取更新后的值
        currentValue = atomicReference.get();
        System.out.println("Current Value: " + currentValue);

        // 尝试更新值,如果当前值是 "Hello",则更新为 "World123"
        updated = atomicReference.compareAndSet("Hello", "World123");
        System.out.println("Updated: " + updated);

        // 获取更新后的值
        currentValue = atomicReference.get();
        System.out.println("Current Value: " + currentValue);
    }
}

更多原子类可以去jdk的java.util.concurrent.atomic包下去查看。


LongAdder

       LongAdder 是 Java 中 java.util.concurrent.atomic 包下的原子操作类,用于高并发环境下对long类型的加法操作。它是在JDK8引入的,相比于 AtomicLong,LongAdder 在高并发情况下表现更好,因为它将内部的值分散到多个变量中,从而降低了竞争。LongAdder引入的初衷解决高并发环境下 AtomicLong 的自旋瓶颈问题。

相关API如下:

add(long x):将当前值增加 x

increment():将当前值增加1。

decrement():将当前值减少1。

sum():获取当前的总和值。注意,这个操作不是原子性的,因此在高并发情况下,它可能不是最准确的。

reset():将当前值重置为0。

import java.util.concurrent.atomic.LongAdder;

public class LongAdderExample {

    public static void main(String[] args) throws InterruptedException {
        LongAdder longAdder = new LongAdder();

        // 创建多个线程并发增加值
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                longAdder.increment();
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                longAdder.increment();
            }
        });

        thread1.start();
        thread2.start();

        // 等待两个线程执行完毕
        thread1.join();
        thread2.join();

        // 获取最终的总和值
        long sum = longAdder.sum();
        System.out.println("Final Sum: " + sum);
    }
}

         除了LongAdder外,还有引入了它的三个兄弟类:LongAccumulator、 DoubleAdder、DoubleAccumulator,感兴趣的可以去java.util.concurrent.atomic去深入了解。

  • 20
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值