AtomicReference自旋加CAS保证对象引用原子性

发布时间:2024年01月06日

AtomicReference类提供了对象引用的非阻塞原子性读写操作,并且提供了其他一些高级的用法,对象的引用其实是一个4字节的数字,代表着在JVM堆内存中的引用地址,对一个4字节数字的读取操作和写入操作本身就是原子性的

package AtomicTest;

import disruptor.WwwApplication;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * desc:
 * author:wangqiangac
 * date:2024/1/5 15:49
 */
@Slf4j
@SpringBootTest(classes= WwwApplication.class)
public class AtomicReferenceTest {

    //volatile DebitCard debitCard = new DebitCard("WangQiang", 0);
    AtomicInteger atomicInteger = new AtomicInteger(0);
    private static AtomicReference debitCardRef = new AtomicReference(new DebitCard("WangQiang",0));
    @Test
    public void test() throws InterruptedException, ExecutionException {
        ThreadPoolBuilder threadPoolBuilder = new ThreadPoolBuilder();
        threadPoolBuilder.setCorePoolSize(50).setMaxPoolSize(100).setKeepAliveSeconds(120).setQueueCapacity(20)
                .setThreadNamePrefix("王强的线程").setPrestartAllCoreThreads(true).setRejectedExecutionHandler(new BlockPolicy());
        ThreadPoolExecutor threadPoolExecutor = threadPoolBuilder.builderThreadPoolExecutor();
        List<Callable<DebitCard>> callables = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            callables.add(()->{
                atomicInteger.getAndIncrement();
                DebitCard debitCard = null;
                DebitCard extracted = extracted();
                return extracted;
            });
        }
        List<Future<DebitCard>> futures = threadPoolExecutor.invokeAll(callables);
        for (Future f: futures) {
            log.error(f.get().toString());
        }
        log.error(debitCardRef.get().toString()+"atomicInteger:"+atomicInteger.get());
    }

    private static DebitCard extracted() {
        DebitCard debitCard;
        debitCard = (DebitCard) debitCardRef.get();
        DebitCard debitCards = new DebitCard(debitCard.getAccount(),debitCard.getAmount()+1);
        if(debitCardRef.compareAndSet(debitCard, debitCards)){
            log.error(debitCards.toString());
            return debitCards;
        }else{
            log.error("和期望的不一样");
            extracted();
            return new DebitCard("出现和期望值不一样自旋了",888);
        }
    }
}

文章来源:https://blog.csdn.net/wq_wangqiang/article/details/135427556
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。