CAS(自旋锁优化)及ABA问题

本文探讨了Java并发中CAS(自旋锁)的工作原理,如何通过weakCompareAndSet避免ABA问题,并介绍了AtomicStampedReference在解决这个问题上的应用。通过实例展示了volatile变量的原子性和ABA问题的解决方案。

CAS (自旋锁 优化)

CAS的全称是 compare and swap,他是同步类的基础, javade concurrent中的原子性都是通过CAS进行实现的

**jdk8**中底层调用的native方法是Unsafe文件中的 compareAndSwap

jdk11中有了升级调用的native方法是 Unsafe文件中 weakCompareAndSet

原理

按照理解,因为是自旋锁优化,实际不是上锁就是在某个线程在改变volatile之前需要验证一下,要改变的值和预期的值是否一致,如果一致则进行变更。通过这种方式保证了volatile变量的原子性。

    /**
     * Atomically adds the given value to the current value of a field
     * or array element within the given object {@code o}
     * at the given {@code offset}.
     *
     * @param o object/array to update the field/element in
     * @param offset field/element offset
     * @param delta the value to add
     * @return the previous value
     * @since 1.8
     */
    @HotSpotIntrinsicCandidate
    public final int getAndAddInt(Object o, long offset, int delta) {
        int v;
        do {
 						// 现获取到当前线程共享的 Volatile
            v = getIntVolatile(o, offset);
          /**
          	o: 代表的是volatile的变量
          	v: 在改变过程中预期的值
          	v + delta: 改变后的值
          */
        } while (!weakCompareAndSetInt(o, offset, v, v + delta));
        return v;
    }

ABA问题

当一个值原本被一个线程读到,准备通过CAS修改的时候,突然因为线程卡住,第二个线程把期望的值改成其他的值后,随后把所期望的值修改回去。第一线程是没有正常执行是无法察觉到的

public class ABA {
    // 模拟两个线程
    static volatile AtomicInteger a = new AtomicInteger(0);

    public static void main(String[] args) {


        final Thread t1 = new Thread(() -> {
            int exceptVal = a.get();
            System.out.println(Thread.currentThread().getName() + " 第一次取到的值: " + exceptVal);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 是否修改成功: " + a.compareAndSet(exceptVal, exceptVal + 1));
        }, "t1");

        final Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            a.incrementAndGet();
            System.out.println(Thread.currentThread().getName() + "increment之后的值:" + a.get());
            a.decrementAndGet();
            System.out.println(Thread.currentThread().getName() + "decrement之后的值:" + a.get());
        }, "t2");
        t1.start();
        t2.start();

    }
}

ABA问题的解决

上述的问题jdk提供了解决方案,通过引入版本号来解决问题 AtomicStampedReference

public class ABA {
    // 模拟两个线程
    // static volatile AtomicInteger a = new AtomicInteger(0);
    static volatile AtomicStampedReference<Integer> a = new AtomicStampedReference<>(0,1);

    public static void main(String[] args) {


        final Thread t1 = new Thread(() -> {
            int exceptVal = a.getReference();
            int exceptStamp = a.getStamp();
            System.out.println(Thread.currentThread().getName() + " 第一次取到的值: " + exceptVal);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 是否修改成功: " + a.compareAndSet(exceptVal, exceptVal + 1,exceptStamp,exceptStamp + 1));
            System.out.println("版本号Stamp:" + a.getStamp());
        }, "t1");

        final Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            a.compareAndSet(a.getReference(), a.getReference() + 1, a.getStamp(), a.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "increment之后的值:" + a.getReference());
            a.compareAndSet(a.getReference(), a.getReference() - 1, a.getStamp(), a.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "decrement之后的值:" + a.getReference());
        }, "t2");
        t1.start();
        t2.start();

    }
}
### 3.1 CAS自旋锁的关系 CAS(Compare-And-Swap)是一种底层的原子操作机制,通常由 CPU 指令直接支持,用于实现多线程环境下的无锁同步。它通过比较并交换两个值的方式,确保在并发操作中数据的一致性[^1]。CAS 本身并不是一种锁,而是一种构建锁机制的基础工具。 自旋锁是一种基于 CAS 实现的同步机制。其核心思想是,当线程尝试获取锁失败时,不会立即进入阻塞状态,而是通过循环不断尝试获取锁,直到成功为止。这种方式减少了线程上下文切换的开销,但会增加 CPU 的使用率[^2]。 ### 3.2 CAS 是否属于自旋锁机制 CAS 本身不属于自旋锁,但它是实现自旋锁的基础。自旋锁的实现通常依赖于 CAS 操作来判断和更新锁的状态。例如,在一个简单的自旋锁实现中,线程会通过 CAS 操作尝试将锁的状态从“未锁定”(如 0)更改为“已锁定”(如 1)。如果操作失败,线程会继续循环尝试,直到成功获取锁为止。以下是基于 CAS自旋锁实现示例: ```java public class SpinLock { private AtomicInteger lock = new AtomicInteger(0); public void lock() { while (!lock.compareAndSet(0, 1)) { // 自旋等待 } } public void unlock() { lock.set(0); } } ``` 上述代码中,`compareAndSet`方法是基于 CAS 实现的原子操作,用于确保锁的获取和释放具有原子性[^3]。 ### 3.3 CAS自旋锁的优缺点 CAS自旋锁都属于乐观并发控制的范畴,适用于低竞争场景[^1]。它们的优点包括减少线程阻塞和上下文切换的开销,从而提高性能。然而,它们也存在一些缺点: - **CAS 的缺点**:在高竞争场景下,CAS 操作可能会频繁失败,导致性能下降。此外,CAS 无法解决“ABA 问题”,即一个值被修改后又恢复为原始值,可能导致错误的判断。 - **自旋锁的缺点**:由于线程在等待锁时会持续循环,因此会消耗较多的 CPU 资源,尤其在锁竞争激烈或持有锁时间较长的情况下。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值