AtomicStampedReference

Posted zheaven

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AtomicStampedReference相关的知识,希望对你有一定的参考价值。

使用AtomicStampedReference解决CAS机制中ABA问题

package concurrency;

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

public class AtomicStampedReferenceTest {
    private static AtomicStampedReference<Integer> atomicref = new AtomicStampedReference<Integer>(100, 0);
    
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    boolean success = atomicref.compareAndSet(100, 101, atomicref.getStamp(), atomicref.getStamp() + 1);
                    System.out.println("t1:=" + success);
                    success = atomicref.compareAndSet(101, 100, atomicref.getStamp(), atomicref.getStamp() + 1);
                    System.out.println("t1:=" + success);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int stamp = atomicref.getStamp();
                    System.out.println("Before sleep:stamp=" + stamp);
                    TimeUnit.SECONDS.sleep(2);
                    boolean success = atomicref.compareAndSet(100, 101, stamp, stamp + 1);
                    System.out.println("t2:=" + success);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}

测试结果:

Before sleep:stamp=0
t1:=true
t1:=true
t2:=false

 

以上是关于AtomicStampedReference的主要内容,如果未能解决你的问题,请参考以下文章

CAS乐观锁使用AtomicStampedReference版本号控制手动实现原子计数

CAS乐观锁使用AtomicStampedReference版本号控制手动实现原子计数

Java 通过原子类 AtomicStampedReference 实现自旋锁

Java AtomicInteger和AtomicStampedReference源码深度解析

CAS乐观锁使用AtomicStampedReference版本号控制手动实现原子计数

CAS乐观锁使用AtomicStampedReference版本号控制手动实现原子计数