Java CAS

Java cas可以理解为compareAndSetVlaue(T expect, T update)或者说compareAndSwapValue(T expect, T update)。比如在AQS中有个int state变量,通过cas原子更新,compareAndSetState(int expect, int update),比较state当前值和expect是否相同,相同更新为update,否则不更新。

CAS原子为了使原子操作不用阻塞线程,减少线程挂起和恢复,线程状态切换的消耗。CAS一次更新不成功可以多次更新,不用挂起线程,切换线程。适合对数据操作时间短的场景。需要CPU提供CAS这种原子指令的支持。

《Java并发编程实战》中给出了CAS模拟代码

SimulateCAS.java
 1 public class SimulateCAS {
 2     private static int index;
 3 
 4     private int value;
 5     public synchronized int get(){
 6         return value;
 7     }
 8 
 9     public synchronized int compareAndSwap(int expectedValue, int newValue){
10         int oldValue = value;
11         if(oldValue == expectedValue)
12             value = newValue;
13         return oldValue;
14     }
15 
16     public synchronized boolean compareAndSet(int expectedValue, int newValue){
17         return (expectedValue == compareAndSwap(expectedValue, newValue));
18     }
19 }

备注:这里使用synchronized会不会造成线程阻塞,需要进一步研究一下

同时,在此基础上封装了一个,类似AtomicInteger功能的类

CasCounter.java
 1 public class CasCounter {
 2     private SimulateCAS value;
 3 
 4     public CasCounter(SimulateCAS value){
 5         this.value = value;
 6     }
 7     public int getValue(){
 8         return value.get();
 9     }
10 
11     public int increment(){
12         int v;
13         do{
14             v = value.get();
15         }while(v != value.compareAndSwap(v, v + 1));
16 
17         return v + 1;
18     }
19 }
原文地址:https://www.cnblogs.com/luckygxf/p/7041548.html