ABA问题及解决办法
生活随笔
收集整理的這篇文章主要介紹了
ABA问题及解决办法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一個線程把數據A變為了B,然后又重新變成了A。此時另外一個線程讀取的時候,發現A沒有變化,就誤以為是原來的那個A。這就是有名的ABA問題。ABA問題會帶來什么后果呢?我們舉個例子。
一個小偷,把別人家的錢偷了之后又還了回來,還是原來的錢嗎,你老婆出軌之后又回來,還是原來的老婆嘛?ABA問題也一樣,如果不好好解決就會帶來大量的問題。最常見的就是資金問題,也就是別人如果挪用了你的錢,在你發現之前又還了回來。但是別人卻已經觸犯了法律。
如何去解決這個ABA問題呢,就是使用下面的AtomicStampedReference。
使用一個版本號去維護,如果發現版本不一致就不更新
class Test {static AtomicInteger balance = new AtomicInteger(100);static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 0);public static void main(String[] args) throws InterruptedException {System.out.println("ABA問題:當前值" + balance.get());//模擬主線程改動變量時,其他線程更改了變量new Thread(() -> System.out.println("thread1:100改成90," + balance.compareAndSet(100, 90))).start();TimeUnit.SECONDS.sleep(1);new Thread(() -> System.out.println("thread2:90改成100," + balance.compareAndSet(90, 100))).start();TimeUnit.SECONDS.sleep(1);//上面的線程改成別的值,然后又改回來,但是主線程沒發現,以為是原來的,所以更改成功了System.out.println("main1:100改成90," + balance.compareAndSet(100, 90));System.out.println("\nABA問題解決:當前值" + atomicStampedReference.getReference());int mstamp = atomicStampedReference.getStamp();System.out.println("main2:當前版本:" + mstamp);//模擬主線程改動變量時,其他線程更改了變量new Thread(() -> {int stamp = atomicStampedReference.getStamp();System.out.println("thread3:100改成90,當前版本=" + atomicStampedReference.getStamp() + "," + atomicStampedReference.compareAndSet(100, 90, stamp, stamp + 1));}).start();TimeUnit.SECONDS.sleep(1);new Thread(() -> {int stamp = atomicStampedReference.getStamp();System.out.println("thread4:90改成100,當前版本=" + atomicStampedReference.getStamp() + "," + atomicStampedReference.compareAndSet(90, 100, stamp, stamp + 1));}).start();TimeUnit.SECONDS.sleep(1);//期間mstamp被更改過,所以這里更新失敗System.out.println("main2:100改成90,當前版本=" + atomicStampedReference.getStamp() + "," + atomicStampedReference.compareAndSet(100, 90, mstamp, mstamp + 1));}}
結果
ABA問題:當前值100
thread1:100改成90,true
thread2:90改成100,true
main1:100改成90,trueABA問題解決:當前值100
main2:當前版本:0
thread3:100改成90,當前版本=0,true
thread4:90改成100,當前版本=1,true
main2:100改成90,當前版本=2,false
總結
以上是生活随笔為你收集整理的ABA问题及解决办法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C - Insertion Sort G
- 下一篇: CAN总线的8种常见故障及解决方法