CAS的ABA问题:原子引用解决

CAS问题:ABA问题(狸猫换太子):
在这里插入图片描述
线程B改变了线程1为3,然后再改回1,线程A却无法知道,仍旧是把1改成了2

package cas;

import java.util.concurrent.atomic.AtomicInteger;

public class CASDemo {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(2020);
        System.out.println(atomicInteger.compareAndSet(2020, 2021));
        System.out.println(atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(2021, 2020));
        System.out.println(atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(2020, 2021));
        System.out.println(atomicInteger.get());
        atomicInteger.getAndIncrement();
    }
}

这是结果:

true
2021
true
2020
true
2021

Process finished with exit code 0

为了解决这个问题,我们采用了原子引用AtomicStampedReference,代码如下:这东西类似于乐观锁,自带版本号。

package cas;

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

public class CASDemo {
    public static void main(String[] args) throws InterruptedException {
        AtomicStampedReference<Integer> atomicInteger = new AtomicStampedReference<>(2020, 1);
        int tamp=atomicInteger.getStamp();

        System.out.println(atomicInteger.compareAndSet(2020, 2021,atomicInteger.getStamp(),atomicInteger.getStamp()+1));

        System.out.println(atomicInteger.compareAndSet(2021, 2020,atomicInteger.getStamp(),atomicInteger.getStamp()+1));
        new Thread(
        ()->{
            System.out.println(atomicInteger.compareAndSet(2020, 2021,atomicInteger.getStamp(),atomicInteger.getStamp()+1));

            System.out.println(atomicInteger.compareAndSet(2021, 2020,atomicInteger.getStamp(),atomicInteger.getStamp()+1));
        }
        ).start();
        TimeUnit.SECONDS.sleep(2);
        System.out.println(atomicInteger.compareAndSet(2020, 2021,tamp,tamp+1));

     }
}

奇怪的是运行全出错,这是因为阿里开发手册揭露Integer大坑

false
false
false
false
false

代码改完后,再运行测试

package cas;

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

public class CASDemo {
    public static void main(String[] args) throws InterruptedException {
        AtomicStampedReference<Integer> atomicInteger = new AtomicStampedReference<>(1, 1);
        int tamp=atomicInteger.getStamp();

         new Thread(
        ()->{
            System.out.println(atomicInteger.compareAndSet(1, 2,atomicInteger.getStamp(),atomicInteger.getStamp()+1));

            System.out.println(atomicInteger.compareAndSet(2, 1,atomicInteger.getStamp(),atomicInteger.getStamp()+1));
        }
        ).start();
        TimeUnit.SECONDS.sleep(2);
        System.out.println(atomicInteger.compareAndSet(1, 2,tamp,tamp+1));

     }
}

成功避免了CAS错误:

true
true
false
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页