AtomicInteger的使用,CAS的工作原理

1.比较并交换Compare-And-Swap

比较当前工作内存的值和主内存的值,如果相同则只需规定操作,否则继续比较直到内存和工作内存中的值一致为止

AtomicInteger atomicInteger = new AtomicInteger(5);
atomicInteger.compareAndSet(5, 2020) + "\t current data is " + atomicInteger.get())

/**
 * Atomically sets the value to the given updated value
 * if the current value {@code ==} the expected value.
 *
 * @param expect the expected value
 * @param update the new value
 * @return {@code true} if successful. False return indicates that
 * the actual value was not equal to the expected value.
 */
public final boolean compareAndSet(int expect, int update) {
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}

2.CAS底层原理

unsafe是CAS的核心类,由于JAVA方法无法直接访问底层系统,需要通过本地native方法来访问,Unsafe相当于一个后门,基于该类可以直接操作特定内存的数据,直接调用操作系统底层资源执行相应任务

private static final Unsafe unsafe =Unsafe.getUnsafe();

CAS并发原语执行是连续的,不允许中断,也就是说CAS是一条CPU的原子指令,不会造成数据不一致问题

3.CAS的缺点

循环时间长开销很大(执行do while循环) 
只能保证一个共享变量的原子操作,对多个共享变量操作时,循环CAS就无法保证操作的原子性,需要用锁
ABA问题
发布了132 篇原创文章 · 获赞 52 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/loulanyue_/article/details/104584352
今日推荐