生活随笔
收集整理的這篇文章主要介紹了
CAS的ABA问题描述 AtomicStampReference
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
CAS的ABA問題描述
- 在CAS操作的時候,其他線程將當前變量的值從A改成B,又改回A;
- CAS線程用期望值A與當前變量比較的時候,發現當前變量沒有變,于是CAS就將當前變量進行了交換操作,但其實當前變量改變過,這與設計思想是不符合的;
- ABA問題的解決思路:每次當前變量更新的時候,將當前變量的版本號加1;
AtomicStampReference示例
- public boolean compareAndSet(
V expectedReference,
V newReference,
int expectedStamp,
int newStamp) - 如果當前值和expectedReference相等,并且當前stamp和expectedStamp相等,把當前值更新為newReference,當前stamp更新為newStamp,并返回true;
- 如果不滿足條件,不更新,并返回false;
import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicStampedReference;public class ABA {private static AtomicInteger atomicInt= new AtomicInteger(100);private static AtomicStampedReference atomicStampedRef= new AtomicStampedReference(100, 0);public static void main(String[] args) throws InterruptedException {Thread intABA = new Thread(new Runnable() {@Overridepublic void run() {atomicInt.compareAndSet(100, 101);atomicInt.compareAndSet(101, 100);}});Thread intCAS = new Thread(new Runnable() {@Overridepublic void run() {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}boolean isUpdated = atomicInt.compareAndSet(100, 101);System.out.println("Thread AtomicInteger CAS isUpdated: " + isUpdated); // true}});intABA.start();intCAS.start();intABA.join();intCAS.join();Thread refABA = new Thread(() -> {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}atomicStampedRef.compareAndSet(100, 101, atomicStampedRef.getStamp(), atomicStampedRef.getStamp() + 1);atomicStampedRef.compareAndSet(101, 100, atomicStampedRef.getStamp(), atomicStampedRef.getStamp() + 1);});Thread refCAS = new Thread(() -> {int stamp = atomicStampedRef.getStamp(); // 0try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {}boolean isUpdated = atomicStampedRef.compareAndSet(100, 101, stamp, stamp + 1);System.out.println("Thread AtomicStampedReference CAS isUpdated: " + isUpdated); // false});refABA.start();refCAS.start();}}
輸出:
Thread AtomicInteger CAS isUpdated: true
Thread AtomicStampedReference CAS isUpdated: false
總結
以上是生活随笔為你收集整理的CAS的ABA问题描述 AtomicStampReference的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。