← 返回并发与锁

🔄 CAS 乐观锁

Compare And Swap —— 不加锁,改的时候检查

📊 CAS 工作流程
读取当前值 expected=5 计算新值 newVal=6 比较:当前值还是5吗? ✅ 是 → 改成6 ❌ 否 → 重试(自旋)
// AtomicInteger 内部就是 CAS AtomicInteger count = new AtomicInteger(0); count.incrementAndGet(); // CAS 实现,无锁 // CAS 伪代码(实际是 CPU 指令 cmpxchg) boolean compareAndSwap(int[] arr, int i, int expected, int newVal) { if (arr[i] == expected) { // 比较 arr[i] = newVal; // 交换 return true; } return false; // 失败,调用方重试 } // 数据库乐观锁:加 version 字段 // UPDATE SET stock=stock-1, version=version+1 // WHERE id=? AND version=?(读时的version) int n = dao.update("...WHERE id=? AND version=?", id, oldVer); if (n == 0) throw new ConcurrentModifyException(); // 被别人改了
ABA 问题:值 5→6→5,CAS 认为没变(还是5),但中间其实变过。解决:加版本号(AtomicStampedReference)。例:转账 A→B→A,看起来没变,但钱动过。
适用:CAS 适合读多写少、冲突少的场景(AtomicInteger/AtomicReference)。高冲突时自旋浪费CPU,不如直接加锁。
并发与锁 · CAS乐观锁 · 全栈资料库