1. 程式人生 > 其它 >Java無鎖方案

Java無鎖方案

技術標籤:casvolatile自旋

1.對於簡單的原子性問題,可以使用CAS+自旋+volatile方案

public class SimulatedCAS {
    volatile int count;
    //實現count += 1;
    void doOne() {
        int newValue, oldValue;
        do {
            oldValue = count;
            newValue = oldValue + 1;
        } while (oldValue != cas(count, newValue));
    }

    //模擬實現CAS,禁用來幫助理解
    synchronized int cas(int expect, int newValue) {
        //讀取當前count的值
        int curValue = count;
        if(curValue == expect) {
            count = newValue;
        }
        return curValue;
    }
}

2.使用無鎖方案的時候需要注意的是ABA問題

可參考的一個解決方案是引入版本號機制