Java無鎖方案
阿新 • • 發佈:2020-12-31
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問題
可參考的一個解決方案是引入版本號機制