Java无锁方案

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问题

可参考的一个解决方案是引入版本号机制

猜你喜欢

转载自blog.csdn.net/m0_37732829/article/details/111962786