多线程(36)AtomicStampedReference

AtomicStampedReference 是 Java 并发包 java.util.concurrent.atomic 中的一个类,它用于解决在使用 CAS(Compare-And-Swap)操作时可能遇到的 ABA 问题。ABA 问题是指,在并发环境中,一个变量原始值为 A,然后被改为 B,最后又被改回 A。使用 CAS 进行比较时,会发现变量的值没有发生变化,从而认为该变量没有被其他线程修改过,CAS 操作成功。但实际上,该变量的值已经被其他线程改变过,这可能会导致错误的结果。

解决ABA问题

AtomicStampedReference 通过维护对象引用以及该引用的一个整数“版本号”来解决 ABA 问题。在执行 CAS 操作时,不仅要求引用相等,还要求版本号相等,从而确保了变量从 A 到 B 再回到 A 的过程中,版本号的变化能够被检测到。

源码解析

AtomicStampedReference 基本结构如下(简化版,去除了部分方法和注释,以便聚焦于主要机制):

public class AtomicStampedReference<V> {
    // Pair 内部类用于同时维护引用和版本号
    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);
        }
    }

    // 实际存储的是 Pair 对象,包含了引用和版本号
    private volatile Pair<V> pair;

    public AtomicStampedReference(V initialRef, int initialStamp) {
        pair = Pair.of(initialRef, initialStamp);
    }

    // 获取当前的引用和版本号
    public V getReference() {
        return pair.reference;
    }

    public int getStamp() {
        return pair.stamp;
    }

    // 原子地更新引用和版本号,只有在期望的引用和版本号都匹配时才更新
    public boolean compareAndSet(V expectedReference, V newReference,
                                  int expectedStamp, int newStamp) {
        Pair<V> current = pair;
        return expectedReference == current.reference && expectedStamp == current.stamp
               && ((newReference == current.reference && newStamp == current.stamp)
                   || casPair(current, Pair.of(newReference, newStamp)));
    }

    // 利用 Unsafe 类完成 CAS 操作
    private boolean casPair(Pair<V> expected, Pair<V> newPair) {
        // 此处的 casPair 是一个原子操作,具体实现依赖于 Unsafe 类
        // 模拟实现,实际实现细节更复杂,依赖于底层硬件
        return UNSAFE.compareAndSwapObject(this, pairOffset, expected, newPair);
    }

    // 其他方法省略...
    private static final Unsafe UNSAFE = Unsafe.getUnsafe();
    private static long pairOffset = ...; // 用于 CAS 操作的偏移量
}

代码演示

以下是一个使用 AtomicStampedReference 的示例,展示了如何利用版本号来防止 ABA 问题:

import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicStampedReferenceDemo {
    public static void main(String[] args) {
        String initialRef = "initial";
        int initialStamp = 0;

        AtomicStampedReference<String> atomicStampedRef =
                new AtomicStampedReference<>(initialRef, initialStamp);

        int[] stampHolder = new int[1];
        String ref = atomicStampedRef.get(stampHolder);

        if (ref.equals("initial") && stampHolder[0] == 0) {
            boolean updated = atomicStampedRef.compareAndSet(ref, "new value", initialStamp, initialStamp + 1);
            System.out.println("Updated: " + updated); // 输出 Updated: true
        }

        // 此时,引用已经被更新为 "new value",版本号增加到 1
        System.out.println("Current Reference: " + atomicStampedRef.getReference());
        System.out.println("Current Stamp: " + atomicStampedRef.getStamp()); // 输出 Current Stamp: 1
    }
}

总结

AtomicStampedReference 提供了一种机制,通过维护每个变量的“版本号”,来避免 CAS 操作的 ABA 问题。这对于实现某些并发算法而言是非常重要的,特别是在涉及到循环 CAS 操作的场景中。通过AtomicStampedReference,我们可以确保即使一个变量的值在多次更新中回到了初始值,这些更新也不会无视中间发生的变化。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

辞暮尔尔-烟火年年

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

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

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

打赏作者

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

抵扣说明:

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

余额充值