Bootstrap

AtomicStampedReference版本号原子引用

如何解决ABA问题

使用AtomicStampedReference版本原子引用类可以解决ABA问题

 

import java.util.concurrent.TimeUnit;

import java.util.concurrent.atomic.AtomicReference;

import java.util.concurrent.atomic.AtomicStampedReference;

 

public class AtomicStampedReferenceDemo {

    public static void main(String[] args) {

        AtomicReference<Integer> atomicReference = new AtomicReference<>(100);

        System.out.println("=============ABA问题产生=============");

        new Thread(() -> {

            System.out.println(Thread.currentThread().getName() + "\t" + atomicReference.compareAndSet(100, 101) + "\t" + atomicReference.get());

            System.out.println(Thread.currentThread().getName() + "\t" + atomicReference.compareAndSet(101, 100) + "\t" + atomicReference.get());

        }, "T1").start();

 

        new Thread(() -> {

            // 先让T1线程执行

            try {

                TimeUnit.SECONDS.sleep(1);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

            System.out.println(Thread.currentThread().getName() + "\t" + atomicReference.compareAndSet(100, 2019) + "\t" + atomicReference.get());

        }, "T2").start();

 

        // ABA问题解决

        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);

        new Thread(() -> {

            int stamp = atomicStampedReference.getStamp();

            // 暂停2秒,等待T2线程执行完毕

            try {

                TimeUnit.SECONDS.sleep(2);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

            System.out.println("=============ABA问题解决=============");

            System.out.println(Thread.currentThread().getName() + "\t第一次版本号:" + stamp + "\t" + atomicStampedReference.compareAndSet(100, 101, stamp, atomicStampedReference.getStamp() + 1));

            System.out.println(Thread.currentThread().getName() + "\t第二次版本号:" + atomicStampedReference.getStamp() + "\t" + atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));

        }, "T3").start();

 

        new Thread(() -> {

            int stamp = atomicStampedReference.getStamp();

            // 暂停3秒,等待T3线程执行完毕

            try {

                TimeUnit.SECONDS.sleep(3);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

            System.out.println(Thread.currentThread().getName() + "\t第三次版本号:" + atomicStampedReference.getStamp() + "\t当前实际值:" + atomicStampedReference.getReference() + "\t" + atomicStampedReference.compareAndSet(100, 2019, stamp, atomicStampedReference.getStamp() + 1));

        }, "T4").start();

    }

}

程序执行结果如下:

 

;