AQS独占模式——资源获取和释放源码分析

发布于:2025-06-14 ⋅ 阅读:(15) ⋅ 点赞:(0)

AQS资源获取(独占模式)

Node节点类

static final class Node {
    //标记当前节点的线程在共享模式下等待。
    static final Node SHARED = new Node();
    
    //标记当前节点的线程在独占模式下等待。
    static final Node EXCLUSIVE = null;
    
    //waitStatus的值,表示当前节点的线程已取消(等待超时或被中断)
    static final int CANCELLED =  1;
    
    //waitStatus的值,表示后继节点的线程需要被唤醒
    static final int SIGNAL    = -1;
    
    //waitStatus的值,表示当前节点在等待某个条件,正处于condition等待队列中
    static final int CONDITION = -2;
    
    //waitStatus的值,表示在当前有资源可用,能够执行后续的acquireShared操作
    static final int PROPAGATE = -3;
 
    //等待状态,值如上,1、-1、-2、-3。
    volatile int waitStatus;
    
    //前趋节点
    volatile Node prev;
 
    //后继节点
    volatile Node next;
    
    //当前线程
    volatile Thread thread;
    
    //等待队列中的后继节点,共享模式下值为SHARED常量
    Node nextWaiter;
    
    //判断共享模式的方法
    final boolean isShared() {
        return nextWaiter == SHARED;
    }
    
    //返回前趋节点,没有报NPE
    final Node predecessor() throws NullPointerException {
        Node p = prev;
        if (p == null)
            throw new NullPointerException();
        else
            return p;
    }
 
    //下面是三个构造方法
    Node() {}    // Used to establish initial head or SHARED marke
    
    Node(Thread thread, Node mode) {     // Used by addWaiter
        this.nextWaiter = mode;
        this.thread = thread;
    }
    Node(Thread thread, int waitStatus) { // Used by Condition
        this.waitStatus = waitStatus;
        this.thread = thread;
    }
}

尝试获取资源,方法分析

    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

获取失败调用addWaiter将当前线程封装成独占模式的节点,添加到AQS队列尾部

	// mode 独占模式 共享模式
    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)) {
            // 刚刚获取的尾节点的后继节点指向新的节点,新节点成为最终尾节点,添加到队列尾部
                pred.next = node;
                return node;
            }
        }
        // 队列没有节点,直接加入队列
        enq(node);
        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;
                }
            }
        }
    }

通过addWaiter已经将当前线程封装成独占模式的 Node 节点,并成功放入队列尾部。接下来会调用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)) {
                // 当前节点设为头节点
                    setHead(node);
                    // 断掉引用
                    p.next = null; // help GC 头节点出列
                    failed = false;
                    return interrupted;
                }
                // 如果不是头节点或获取锁失败 准备阻塞
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
            // 取消同步状态
                cancelAcquire(node);
        }
    }

//将当前节点设置为头节点
private void setHead(Node node) {
    head = node;
    node.thread = null;
    node.prev = null;
}
// 判断当前线程是否可以进入waiting状态
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
// 获取前驱节点的等待状态
        int ws = pred.waitStatus;
        if (ws == Node.SIGNAL) // 可以被唤醒
            return true;
        if (ws > 0) { // 表示当前线程被取消
            do {
            // 关键  节点一直往前移动,直到找到状态<=0的节点
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
        // 下面节点进来的条件,前驱节点是SIGNAL,这里设置为SIGNAL
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }
    	// 挂起线程
 private final boolean parkAndCheckInterrupt() {
      LockSupport.park(this);
      return Thread.interrupted();
}

protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            // 判断是否0
            int c = getState();
            if (c == 0) {
                if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {
                    // 设为当前线程
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            // 不为0 尝试获取锁
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
}

获取资源的整体流程图如下:

AQS资源获取(独占模式)特点

1.互斥访问(Mutual Exclusion)

  • 单线程持有:同一时间只允许一个线程持有资源
  • 状态管理:通过 state 变量(volatile int)表示资源状态
  • CAS操作:使用 compareAndSetState 确保状态更新原子性
  • 示例:ReentrantLock 中 state=0 表示未锁定,state>0 表示锁定状态

2. 线程阻塞队列(CLH Queue)

  • FIFO队列:使用双向链表实现的 CLH 变体队列
  • 节点类型:Node.EXCLUSIVE 表示独占模式节点
  • 排队机制:获取资源失败的线程会被封装为节点加入队列尾部

3. 可重入支持(Reentrancy)

  • 重入计数:state 变量记录重入次数
  • 持有线程:通过 exclusiveOwnerThread 记录当前持有线程
  • 示例:ReentrantLock 允许线程多次获取同一把锁

在这里插入图片描述

AQS资源释放(独占模式)

    public void unlock() {
        sync.release(1);
    }

    public final boolean release(int arg) {
        if (tryRelease(arg)) {
            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)
        // <0 尝试设置为0
            node.compareAndSetWaitStatus(ws, 0);
		
		// 获取节点后继
        Node s = node.next;
        // 后继节点为空或等待状态>0 节点取消
        if (s == null || s.waitStatus > 0) {
            s = null;
            // 从尾部向前遍历
            for (Node p = tail; p != node && p != null; p = p.prev)
                if (p.waitStatus <= 0)
                    s = p;
        }
        // 不为空,准备进行唤醒操作
        if (s != null)
        // 线程停止阻塞
            LockSupport.unpark(s.thread);
    }

AQS 资源释放(独占模式)流程图
在这里插入图片描述

AQS资源释放(独占模式)特点

1.状态更新:

  • 通过 tryRelease 更新同步状态
  • 清除当前持有线程

2.唤醒策略:

  • 只唤醒头节点的下一个有效节点
  • 采用从后向前查找策略解决并发入队问题

3.线程安全:

  • 使用 CAS 更新 waitStatus
  • 无锁化设计确保高性能

4.取消处理:

  • 自动跳过已取消节点(waitStatus > 0)
  • 确保唤醒的节点都是有效等待节点