← 返回首页 📚 实战课程
📑 本篇章节导航 (共5章,点击直达)
本节目标(学完能回答的面试题)核心知识(1小时精讲内容)面试速记卡(考前30秒速看)练习题(自测)学习资料

L02 - AQS完整原理

本节目标(学完能回答的面试题)

核心知识(1小时精讲内容)

一、AQS设计思想

AbstractQueuedSynchronizer(AQS)是java.util.concurrent包的核心框架,Doug Lea设计。

核心理念:模板方法模式 —— AQS负责排队阻塞,子类负责定义"能否获取/释放"的规则。


AQS三大核心组件:

  +---------------------------------------------------+
  |              AbstractQueuedSynchronizer            |
  |                                                    |
  |  1. volatile int state    ← 同步状态(0/1/N)       |
  |                                                    |
  |  2. CLH变体队列(FIFO)    ← 等待线程排队           |
  |     head → Node ↔ Node ↔ Node ... ← tail          |
  |                                                    |
  |  3. 模板方法               ← 子类实现tryAcquire等   |
  |     tryAcquire(int)                                 |
  |     tryRelease(int)                                 |
  |     tryAcquireShared(int)                           |
  |     tryReleaseShared(int)                           |
  |     isHeldExclusively()                             |
  +---------------------------------------------------+

state的含义因实现而异:

实现类state含义独占/共享
ReentrantLock0=未锁定, 1=锁定, N=重入次数独占
CountDownLatch剩余计数(countDown递减至0)共享
Semaphore剩余许可数共享
ReentrantReadWriteLock高16位=读锁持有数, 低16位=写锁重入数读共享/写独占

二、CLH变体队列结构


CLH队列(Craig, Landin, and Hagersten queue 变体):

     head                tail
      │                   │
      ▼                   ▼
  +--------+    +--------+    +--------+
  | Node   | ←─ | Node   | ←─ | Node   |
  | (哨兵) | ─→ | ThreadB| ─→ | ThreadC|
  | ws=SIGNAL|  | ws=0   |    | ws=0   |
  +--------+    +--------+    +--------+

Node关键字段:
  volatile int waitStatus;    // 节点状态
  volatile Node prev;         // 前驱节点
  volatile Node next;         // 后继节点
  volatile Thread thread;     // 等待的线程
  Node nextWaiter;            // Condition队列的后继(或标记共享/独占模式)

waitStatus取值:
  CANCELLED  =  1  ← 线程已取消(超时/中断)
  SIGNAL     = -1  ← 后继线程需要被唤醒(park)
  CONDITION  = -2  ← 在Condition等待队列中
  PROPAGATE  = -3  ← 共享模式传播唤醒
  0               ← 初始状态

三、独占模式源码分析(ReentrantLock为例)

获取锁:acquire(int arg)


// AQS核心入口
public final void acquire(int arg) {
    if (!tryAcquire(arg) &&                    // ① 尝试获取锁
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) // ② 入队+自旋/阻塞
        selfInterrupt();                       // ③ 补上中断标记
}

① tryAcquire —— 子类实现(以ReentrantLock.NonfairSync为例)


// NonfairSync.tryAcquire(非公平锁)
final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) {
        // state=0,无锁,CAS尝试获取
        if (compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);
            return true;
        }
    }
    else if (current == getExclusiveOwnerThread()) {
        // 当前线程已持有,重入
        int nextc = c + acquires;
        if (nextc < 0) throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    return false;
}

② addWaiter —— 入队


private Node addWaiter(Node mode) {
    Node node = new Node(Thread.currentThread(), mode);
    // 快速尝试在尾部添加
    Node pred = tail;
    if (pred != null) {
        node.prev = pred;
        if (compareAndSetTail(pred, node)) { // CAS设置tail
            pred.next = node;
            return node;
        }
    }
    enq(node); // CAS失败 → 自旋入队(保证成功)
    return node;
}

private Node enq(final Node node) {
    for (;;) {  // 自旋
        Node t = tail;
        if (t == null) { // 队列为空,初始化哨兵节点
            if (compareAndSetHead(new Node()))
                tail = head;
        } else {
            node.prev = t;
            if (compareAndSetTail(t, node)) {
                t.next = node;
                return t;
            }
        }
    }
}

③ acquireQueued —— 自旋获取/挂起


final boolean acquireQueued(final Node node, int arg) {
    boolean failed = true;
    try {
        boolean interrupted = false;
        for (;;) {  // 自旋
            final Node p = node.predecessor();
            if (p == head && tryAcquire(arg)) {
                // 前驱是head且获取成功 → 出队
                setHead(node);
                p.next = null; // help GC
                failed = false;
                return interrupted;
            }
            if (shouldParkAfterFailedAcquire(p, node) && // 判断是否应该挂起
                parkAndCheckInterrupt())                  // LockSupport.park挂起
                interrupted = true;
        }
    } finally {
        if (failed) cancelAcquire(node);
    }
}

shouldParkAfterFailedAcquire —— 判断是否应挂起


private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
    int ws = pred.waitStatus;
    if (ws == Node.SIGNAL)
        // 前驱已经设置了SIGNAL,可以安全挂起
        return true;
    if (ws > 0) {
        // 前驱已取消,跳过所有已取消的前驱
        do {
            node.prev = pred = pred.prev;
        } while (pred.waitStatus > 0);
        pred.next = node;
    } else {
        // 前驱状态为0或PROPAGATE,CAS设置为SIGNAL
        compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
    }
    return false;
}

释放锁:release(int arg)


public final boolean release(int arg) {
    if (tryRelease(arg)) {           // ① 子类实现,state-1
        Node h = head;
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h);       // ② 唤醒后继节点
        return true;
    }
    return false;
}

private void unparkSuccessor(Node node) {
    int ws = node.waitStatus;
    if (ws < 0) compareAndSetWaitStatus(node, ws, 0);
    Node s = node.next;
    if (s == null || s.waitStatus > 0) {
        // 后继为空或已取消,从尾部向前找第一个未取消的
        s = null;
        for (Node t = tail; t != null && t != node; t = t.prev)
            if (t.waitStatus <= 0) s = t;
    }
    if (s != null) LockSupport.unpark(s.thread); // 唤醒线程
}

四、共享模式源码分析

获取:acquireShared(int arg)


public final void acquireShared(int arg) {
    if (tryAcquireShared(arg) < 0)  // 返回负数表示获取失败
        doAcquireShared(arg);
}

private void doAcquireShared(int arg) {
    final Node node = addWaiter(Node.SHARED);
    boolean failed = true;
    try {
        boolean interrupted = false;
        for (;;) {
            Node p = node.predecessor();
            if (p == head) {
                int r = tryAcquireShared(arg);
                if (r >= 0) {
                    setHeadAndPropagate(node, r); // 关键:传播唤醒!
                    p.next = null;
                    if (interrupted) selfInterrupt();
                    failed = false;
                    return;
                }
            }
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed) cancelAcquire(node);
    }
}

setHeadAndPropagate —— 共享模式独有的传播唤醒:


head → [持有锁] → NodeA(SHARED) → NodeB(SHARED)
                    │                  │
                    └── 获取成功后 ─────└── 传播唤醒B
                    (独占模式不会传播!)

五、三大实现类对比

ReentrantLock(独占模式)


// 非公平锁 tryAcquire
state: 0→1 获取锁, 1→N 重入, N→0 释放锁

// 公平锁 tryAcquire(FairSync)
// 区别仅在于:CAS前先检查队列中是否有等待线程
if (c == 0 && !hasQueuedPredecessors() && compareAndSetState(0, acquires))

CountDownLatch(共享模式)


// tryAcquireShared:state==0时返回1(允许),否则返回-1(阻塞)
int tryAcquireShared(int acquires) {
    return (getState() == 0) ? 1 : -1;
}

// tryReleaseShared:countDown递减state
boolean tryReleaseShared(int releases) {
    for (;;) {
        int c = getState();
        if (c == 0) return false;
        int nextc = c - 1;
        if (compareAndSetState(c, nextc))
            return nextc == 0; // state减到0时返回true,触发唤醒所有等待线程
    }
}

Semaphore(共享模式)


// tryAcquireShared:state为剩余许可数
int tryAcquireShared(int acquires) {
    for (;;) {
        int available = getState();
        int remaining = available - acquires;
        if (remaining < 0 ||
            compareAndSetState(available, remaining))
            return remaining; // 负数=阻塞,非负=成功
    }
}

// tryReleaseShared:release增加许可
boolean tryReleaseShared(int releases) {
    for (;;) {
        int current = getState();
        int next = current + releases;
        if (compareAndSetState(current, next))
            return true;
    }
}

六、AQS完整流程图


┌────────────────────────────────────────────────────────────────┐
│                    AQS acquire 独占模式                         │
├────────────────────────────────────────────────────────────────┤
│                                                                │
│  acquire(arg)                                                  │
│    │                                                           │
│    ├─ tryAcquire(arg) ──成功──→ 返回(获取锁成功)               │
│    │                                                           │
│    └─ 失败                                                     │
│       │                                                        │
│       ▼                                                        │
│    addWaiter(EXCLUSIVE)                                        │
│       │                                                        │
│       ▼                                                        │
│    acquireQueued(node, arg)                                    │
│       │                                                        │
│       ├── 自旋:前驱是head && tryAcquire成功 → 出队,返回        │
│       │                                                        │
│       └── 失败:shouldParkAfterFailedAcquire                   │
│              │                                                 │
│              ├── 前驱ws==SIGNAL → parkAndCheckInterrupt        │
│              │                    (LockSupport.park挂起)        │
│              │                                                 │
│              ├── 前驱ws>0(取消) → 跳过已取消节点,重试           │
│              │                                                 │
│              └── 其他 → CAS设置前驱ws=SIGNAL,重试              │
│                                                                │
├────────────────────────────────────────────────────────────────┤
│                    AQS release 独占模式                         │
├────────────────────────────────────────────────────────────────┤
│                                                                │
│  release(arg)                                                  │
│    │                                                           │
│    ├─ tryRelease(arg) ──失败──→ 返回false                      │
│    │                                                           │
│    └─ 成功                                                     │
│       │                                                        │
│       ▼                                                        │
│    unparkSuccessor(head)                                       │
│       │                                                        │
│       ├── 后继未取消 → LockSupport.unpark唤醒后继线程           │
│       │                                                        │
│       └── 后继取消 → 从tail向前遍历找到第一个未取消的节点唤醒    │
│                                                                │
└────────────────────────────────────────────────────────────────┘

七、面试追问与回答

Q1: 为什么AQS用CLH队列而不是普通队列?

CLH队列基于前驱节点的状态来判断是否应该挂起,入队和出队都只需对tail/head做CAS操作,不需要全局锁。且CLH队列便于处理取消节点和超时节点。

Q2: 为什么从tail向前遍历找后继节点?

因为enq入队时先设置node.prev再CAS tail最后设置pred.next,所以prev指针是可靠的,而next指针可能在CAS成功后还未设置。

Q3: 公平锁和非公平锁的区别?

非公平锁在tryAcquire时不检查队列,直接CAS竞争;公平锁在CAS前先调用hasQueuedPredecessors()检查队列中是否有等待更久的线程。非公平吞吐量更高但可能导致饥饿。

Q4: AQS为什么用volatile int state而不是AtomicInteger?

AQS内部使用CAS(compareAndSetState)直接操作volatile int,比AtomicInteger少一层间接调用。state的volatile保证了可见性,CAS保证了原子性,不需要AtomicInteger的额外封装。

Q5: 共享模式的"传播唤醒"是什么意思?

共享模式下(如Semaphore),一个线程释放资源后,如果还有剩余资源,会继续唤醒后续的共享节点,直到资源耗尽或队列为空。这就是"传播"——唤醒不止一个线程。

面试速记卡(考前30秒速看)

练习题(自测)

1. 手绘AQS CLH队列结构,标注head/tail/prev/next/waitStatus,并解释入队过程。

2. 对比公平锁和非公平锁的tryAcquire源码差异,分析非公平锁为什么吞吐量更高。

3. 用AQS实现一个简单的不可重入互斥锁(MyMutex),只需实现tryAcquire和tryRelease。

4. 解释CountDownLatch的countDown()和await()如何通过AQS的共享模式实现。

5. 如果一个等待线程被中断,AQS如何处理?(提示:cancelAcquire清理节点链表)

学习资料