You need to enable JavaScript to run this app. 基于CAS实现的非阻塞线程安全计数器并发运行异常原因排查
优惠活动
大模型
产品
解决方案
定价
更多

基于CAS实现的非阻塞线程安全计数器并发运行异常原因排查

问题根因分析
  • 共享变量滥用:你将oldValue、newValue定义为类的成员原子变量,所有线程操作的是同一份实例,多线程并发时会互相覆盖值,完全破坏了CAS操作的正确性。
  • 新值计算逻辑错误:newValue的计算没有基于当前拿到的oldValue做+1,而是直接对共享的newValue做自增,和计数器当前的实际值完全解耦。
  • 冗余实现:用AtomicReference<Integer>存储计数完全没必要,直接使用AtomicInteger更简洁高效。
修复后的代码

修正后的CASCount实现如下,测试用例无需修改即可通过:

public class CASCount {
    // 直接用AtomicInteger存计数,无需额外包装
    private final AtomicInteger count = new AtomicInteger(0);

    public void increment() {
        int oldVal;
        int newVal;
        do {
            // 每次循环取当前最新的计数值,存入局部变量(线程私有,不会被其他线程修改)
            oldVal = count.get();
            if (oldVal == -1) {
                throw new UnsupportedOperationException("Count is not impl.");
            }
            // 新值严格基于本次拿到的旧值计算
            newVal = oldVal + 1;
        // CAS尝试替换,失败则自动循环重试
        } while (!count.compareAndSet(oldVal, newVal));
    }

    public int get() {
        int result = count.get();
        if (result == -1) {
            throw new UnsupportedOperationException("Count is not impl.");
        }
        return result;
    }
}
兼容AtomicReference的可选实现

如果一定要保留AtomicReference<Integer>的实现方式,只要把oldValue、newValue改为方法内的局部变量即可,不要作为成员变量共享:

public class CASCount {
    private final AtomicReference<Integer> count = new AtomicReference<>(0);

    public void increment() {
        Integer oldVal;
        Integer newVal;
        do {
            oldVal = count.get();
            if (oldVal == -1) {
                throw new UnsupportedOperationException("Count is not impl.");
            }
            newVal = oldVal + 1;
        } while (!count.compareAndSet(oldVal, newVal));
    }

    public int get() {
        int result = count.get();
        if (result == -1) {
            throw new UnsupportedOperationException("Count is not impl.");
        }
        return result;
    }
}

内容的提问来源于stack exchange,提问作者Terasan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 08:45:10