什么是CAS? compare and swap
参考博文: https://objcoding.com/2018/11/29/cas/
CAS的等价代码
/**
* @Classname SimulatedCAS
* @Description 模拟CAS操作,java实验CAS基本思想
* @Date 2021/2/18 15:13
* @Created by YoungLiu
*/
public class TwoThreadsCompetition implements Runnable{
private volatile int value;
public synchronized int compareAndSwap(int expectedValue,int newValue){
int oldValue = value;
if(oldValue==expectedValue){
value=newValue;
}
return oldValue;
}
public static void main(String[] args) throws InterruptedException {
TwoThreadsCompetition r = new TwoThreadsCompetition();
r.value=0;
Thread t1 = new Thread(r,"Thread1");
Thread t2 = new Thread(r,"Thread2");
t1.start();
t2.start();
t1.join();
t2.join();
//此处会输出 1, 但只有一个线程成功修改了值。
System.out.println(r.value);
}
@Override
public void run() {
compareAndSwap(0,1);
}
}
CAS的应用场景
- 乐观锁
- 并发容器
- 原子类
上述都的底层体现了CAS的基本思想。
AtomicInteger是如何实现CAS的?
CAS的缺点
ABA问题
图片源于:https://juejin.cn/post/6844903796129136647