ReentrantLock源码解读(1)——CAS

ReentrantLock源码系列 ReentrantLock源码解读(1)——CAS ReentrantLock源码解读(2)——ReentrantLock源

ReentrantLock源码系列
ReentrantLock源码解读(1)——CAS
ReentrantLock源码解读(2)——ReentrantLock源码与AQS
ReentrantLock源码解读(3)——Condition

进入源码前先介绍一个“无锁”技术:CAS(compare and swap)。为什么要介绍它呢,因为ReentrantLock的锁就是利用它实现的。
它是一种乐光的策略,就是乐观地认为访问资源是不会冲突的,也就是所有的线程都可以不等待地进行下去。遇到冲突怎么办?检测到冲突就是一直重试,直到没有冲突为止。
简单说,CAS需要你额外给定一个期望值,也就是你认为这个状态是什么样子,如果不是,就说明被人改过了,那就重新读取、设定期望值,再次尝试修改。

  • 例子
public class CASTest {static AtomicInteger atomicInteger = new AtomicInteger();static class Increment implements Runnable {@Overridepublic void run() {for (int i = 0; i < 1000; i++) {atomicInteger.incrementAndGet();