栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【八股文】一分钟掌握ABA问题以及解决办法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【八股文】一分钟掌握ABA问题以及解决办法

目录

使用AtomicStampedReference 解决ABA问题

示例代码

 使用AtomicMarkableReference解决问题

示例代码


什么是ABA

有一个链表里面的数据是A->B->C,我们希望执行一个CAS操作,将A替换成D,生成链表D->B->C。考虑下面的步骤:

  1. 线程a读取链表头部节点A。
  2. 线程b将链表中的B节点删掉,链表变成了A->C
  3. 线程a执行CAS操作,将A替换从D。

最后我们的到的链表是D->C,而不是D->B->C,这个就是ABA问题。那么如何解决这个问题呢?下面就介绍两种解决ABA的方法。

使用AtomicStampedReference 解决ABA问题

JDK提供了AtomicStampedReference来解决ABA问题,它在CAS的基础上增加了一个邮戳stamp来标记数据是否发生了变化。,如果邮戳不符合预期则修改失败。

示例代码
public class AtomicStampedReferenceTest {

    public void test() {
        CountDownLatch latch = new CountDownLatch(2);
        AtomicStampedReference atomicStampedReference = new AtomicStampedReference<>(1, 0);
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.submit(() -> {
            try {
                boolean success;
                //获取当前邮戳
                int stamp = atomicStampedReference.getStamp();
                System.out.println("[A] before sleep  value is " + atomicStampedReference.getReference() + " stamp is " + stamp);
                TimeUnit.SECONDS.sleep(5);
                //将1,改为 10
                success = atomicStampedReference.compareAndSet(1, 10, stamp, stamp + 1);
                System.out.println("[A-1] after sleep, success:  " + success + "  value is " + atomicStampedReference.getReference() + " stamp is " + stamp);
                stamp++;
                //再次将10 改为1 
                atomicStampedReference.compareAndSet(10, 1, stamp, stamp + 1);
                System.out.println("[A-2] after sleep, success:  " + success + "  value is " + atomicStampedReference.getReference() + " stamp is " + stamp);
                latch.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

        executorService.submit(() -> {
            try {
                boolean success;
                int stamp = atomicStampedReference.getStamp();
                System.out.println("[B] before sleep  value is " + atomicStampedReference.getReference() + " stamp is " + stamp);
                TimeUnit.SECONDS.sleep(10);
                success = atomicStampedReference.compareAndSet(1, 20, stamp, stamp + 1);
                System.out.println("[B-1] after sleep, success:  " + success + "  value is " + atomicStampedReference.getReference() + " stamp is " + stamp);
                latch.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public static void main(String[] args) {
        new AtomicStampedReferenceTest().test();
    }
}

测试结果如下:

[A] before sleep  value is 1 stamp is 0
[B] before sleep  value is 1 stamp is 0
[A-1] after sleep, success:  true  value is 10 stamp is 0
[A-2] after sleep, success:  true  value is 1 stamp is 1
[B-1] after sleep, success:  false  value is 1 stamp is 0

 使用AtomicMarkableReference解决问题

        上文我们使用AtomicStampedReference来解决ABA问题,很多时候我们并不关心它的邮戳,也就是我们不需要知道修改过几次,我们关系的仅仅是有没有修改过。此时我们就可以使用AtomicMarkableReference来解决这个问题。

示例代码
public class AtomicMarkableReferenceTest {

    public void test() {
        CountDownLatch latch = new CountDownLatch(2);
        AtomicMarkableReference atomicMarkableReference = new AtomicMarkableReference<>(1, false);
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.submit(() -> {
            try {
                boolean success;
                //获取当前邮戳
                boolean[] arr = new boolean[]{false};
                Integer currentValue = atomicMarkableReference.get(arr);
                boolean mark = arr[0];

                System.out.println("[A] before sleep  value is " + currentValue + " mark is " + mark);
                TimeUnit.SECONDS.sleep(5);
                //将1,改为 10
                success = atomicMarkableReference.compareAndSet(1, 1, mark, !mark);
                System.out.println("[A-1] after sleep, success:  " + success + "  value is " + atomicMarkableReference.getReference() + " mark is " + getMark(atomicMarkableReference));
                latch.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

        executorService.submit(() -> {
            try {
                boolean success;
                //获取当前邮戳
                boolean[] arr = new boolean[]{false};
                Integer currentValue = atomicMarkableReference.get(arr);
                boolean mark = arr[0];
                System.out.println("[B] before sleep  value is " + currentValue + " mark is " + mark);
                TimeUnit.SECONDS.sleep(10);
                success = atomicMarkableReference.compareAndSet(1, 20, mark, !mark);
                System.out.println("[B-1] after sleep, success:  " + success + "  value is " + atomicMarkableReference.getReference() + " mark is " + getMark(atomicMarkableReference));
                latch.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private boolean getMark(AtomicMarkableReference atomicMarkableReference) {
        boolean[] arr = new boolean[]{false};
        atomicMarkableReference.get(arr);
        return arr[0];
    }

    public static void main(String[] args) {
        new AtomicMarkableReferenceTest().test();
    }
}

测试结果

[A] before sleep  value is 1 mark is false
[B] before sleep  value is 1 mark is false
[A-1] after sleep, success:  true  value is 1 mark is true
[B-1] after sleep, success:  false  value is 1 mark is true

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/978809.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号