1、前置知识

  • 公平锁和非公平锁
  • 可重入锁
  • LockSupport
  • 自旋锁
  • 数据结构之链表
  • 设计模式之模板设计模式

2、AQS(AbstractQueuedSynchronizer) 是什么

java.util.concurrent.locks.AbstractQueuedSynchronizer,抽象的队列同步器
image.png
AQS 是用来构建锁或者其他同步器组件的重量级基础框架及整个 JUC 体系的基石,通过内置的 FIFO队列来完成资源获取线程的排队工作,并通过一个 int 类型的变量表示持有锁的状态。
image.png
CLH:Craig、Landin and Hagersten 队列,是一个单向链表,AQS中的队列是CLH变体的虚拟双向队列FIFO

3、AQS 为什么JUC 体系的基石

和AQS 有关的类

  • ReentrantLock
  • CountDownLatch
  • ReentrantReadWriteLock
  • Semaphore
  • ……

锁和同步器的关系

  • 锁:面向锁的使用者,定义了程序员和锁交互的使用层API,隐藏了实现细节,你调用即可。
  • 同步器:面向锁的实现者,比如Java并发大神DougLee,提出统一规范并简化了锁的实现,屏蔽了同步状态管理、阻塞线程排队和通知、唤醒机制等

4、AQS 能干嘛

加锁导致阻塞,有阻塞就需要排队,实现排队必然需要有某种形式的队列来管理
抢到资源的线程直接使用处理业务逻辑,抢不到资源的必然涉及一种排队等候机制。抢占资源失败的线程继续去等待(类似银行业务办理窗口都满了,暂时没有受理窗口的顾客只能去候客区排队等候),但等待线程仍然保留获取锁的可能且获取锁流程仍在继续(候客区的顾客也在等待叫号,轮到了再去受理窗口办理业务)。
既然说到了排队等候机制,那么就一定会有某种队列形成
如果共享资源被占用,就需要一定的阻塞等待唤醒机制来保证锁分配。这个机制主要用的是 CLH 队列的变体实现的,将暂时获取不到锁的线程加入到队列中,这个队列就是 AQS 的抽象表现。它将请求共享资源的线程封装成队列的节点(Node),通过 CAS、自旋以及 LockSupport.park() 的方式,维护 state 变量的状态,使并发达到同步的控制效果。

5、AQS 初步

官网解释

Provides a framework for implementing blocking locks and related synchronizers (semaphores, events, etc) that rely on first-in-first-out (FIFO) wait queues. This class is designed to be a useful basis for most kinds of synchronizers that rely on a single atomic int value to represent state. Subclasses must define the protected methods that change this state, and which define what that state means in terms of this object being acquired or released. Given these, the other methods in this class carry out all queuing and blocking mechanics. Subclasses can maintain other state fields, but only the atomically updated int value manipulated using methods getState, setState and compareAndSetState is tracked with respect to synchronization.

提供一个框架,用于实现依赖于先进先出(FIFO)等待队列的阻塞锁和相关的同步器(信号灯,事件等)。 此类旨在为大多数依赖单个原子int值表示状态的同步器提供有用的基础。 子类必须定义更改此状态的受保护方法,并定义该状态对要获取或释放的对象而言意味着什么。 有了这些,该类中的其他方法将执行所有排队和阻塞机制。 子类可以维护其他状态字段,但是相对于同步,仅跟踪使用方法getState , setState和compareAndSetState操作的原子更新的int值。

有阻塞就需要排队,实现排队必然需要队列
AQS 使用一个 volatile 的 int 类型的成员变量来表示同步状态,通过内置的 FIFO 队列来完成资源获取的排队工作,将每条要去抢占资源的线程封装成一个 Node 节点来实现锁的分配,通过 CAS 完成对 State 值的修改。

  1. public abstract class AbstractQueuedSynchronizer
  2. extends AbstractOwnableSynchronizer
  3. implements java.io.Serializable {
  4. private static final long serialVersionUID = 7373984972572414691L;
  5. protected AbstractQueuedSynchronizer() { }
  6. static final class Node {...}
  7. private transient volatile Node head;
  8. private transient volatile Node tail;
  9. /**同步状态。*/
  10. private volatile int state;
  11. ...
  12. }

AQS 内部体系架构

image.png

AQS 自身

AQS 的 int 变量,AQS 的同步状态 State 成员变量

private volatile int state;

AQS 的 CLH 队列,为一个双向队列

AQS 内部类 node

static final class Node {
       // 共享
        static final Node SHARED = new Node();

        // 独占
        static final Node EXCLUSIVE = null;

        // 线程被取消了 
        static final int CANCELLED =  1;

        // 后继线程被唤醒
        static final int SIGNAL    = -1;

        // 等待 condition 唤醒
        static final int CONDITION = -2;

        // 共享式同步状态获取将无条件地传播下去
        static final int PROPAGATE = -3;

        // 初始为 0 ,状态是上面几种
        volatile int waitStatus;

        // 前置节点
        volatile Node prev;

        // 后继节点
        volatile Node next;

        volatile Thread thread;

        Node nextWaiter;

        final boolean isShared() {
            return nextWaiter == SHARED;
        }

        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 marker
        }

        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;
        }
    }
  • SHARED:表示线程以共享的模式等待锁
  • EXCLUSIVE:表示线程以独占的方式等待锁
  • waitStatus:当前节点在队列中的状态
    • 0:当一个 Node 被初始化的时候的默认值
    • 1:CANCELLED:表示线程获取锁的请求已经取消了
    • -2:CONDITION:表示节点在等待队列中,节点线程等待唤醒
    • -3:PROPAGATE:当前线程出在 SHARED 情况下,该字段才会使用
    • -1:SIGNAL:表示线程已经准备好了,就等资源释放了
  • thread:表示处于该节点的线程
  • next:前驱指针
  • nextWaiter:指向下一个处于 CONDITION 状态的节点
  • next:后继指针

6、从 ReentrantLock 开始解读 AQS

Lock 接口的实现类,基本都是通过聚合了一个队列同步器的子类完成线程访问控制的。

public class ReentrantLock implements Lock, java.io.Serializable {

    abstract static class Sync extends AbstractQueuedSynchronizer {}

    static final class NonfairSync extends Sync {}

    static final class FairSync extends Sync {}

    //默认创建非公平锁
    public ReentrantLock() {
        sync = new NonfairSync();
    }

    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }
}

从简单的 lock 方法看看公平和非公平

            // 公平锁    
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (!hasQueuedPredecessors() &&  // 比非公平锁就多了这一行
                    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;
        }

    // 非公平锁
    final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

对比公平锁与非公平锁的 tryAcquire方法的实现代码,区别就在于公平锁在获取同步状态时多了一个限制条件:hasQueuedPredecessors()
hasQueuedPredecessors():是公平锁加锁时判断等待队列中是否存在有效节点的方法,判断了是否需要排队

  • 公平锁:公平锁讲究先来先到,线程在获取锁时,如果这个锁的等待队列中已经有线程在等待,那么当前线程就会进入等待队列中
  • 非公平锁:不管是否有等待队列,如果可以获取锁,则立即占有锁对象。也就是说队列的第一个排队线程在 unpark()之后还是需要竞争锁(存在线程竞争的情况下) ```java static final class FairSync extends Sync {

      final void lock() {
          acquire(1);
      }
    

    }

static final class NonfairSync extends Sync {

    final void lock() {
        if (compareAndSetState(0, 1))
            setExclusiveOwnerThread(Thread.currentThread());
        else
            acquire(1);
    }

}


整个 ReentrantLock 的加锁过程,可以分为三个阶段:

1. 尝试加锁
1. 加锁失败,线程入队列
1. 线程入队列后,进入阻塞状态

![image.png](https://cdn.nlark.com/yuque/0/2021/png/8431753/1640058902605-c57789ed-b574-458e-97c7-5f0ecbc3342e.png#clientId=u19cc1989-8f64-4&from=paste&height=195&id=uc9524ce0&margin=%5Bobject%20Object%5D&name=image.png&originHeight=195&originWidth=333&originalType=binary&ratio=1&size=5780&status=done&style=none&taskId=u38fe4cd8-b8bd-4367-b0a5-03bc52738be&width=333)
<a name="Uc8Ps"></a>
### 非公平锁方法lock()
```java
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        /**
         * 执行锁定。 尝试立即抢占,在失败时备份到正常获取。
         */
        final void lock() {
            if (compareAndSetState(0, 1))
                // 第一个线程抢占
                setExclusiveOwnerThread(Thread.currentThread());
            else
                // 第二个线程以及后续线程抢占
                acquire(1);
        }
    }

acquire()

    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
  1. 调用 tryAcquire(交由子类 nonfairTryAcquire 实现)
  2. 调用 addWaiter ,enq 入队操作
  3. 调用 acquireQueued ,调用 cancelAcquire

    tryAcquire(arg)

         protected final boolean tryAcquire(int acquires) {
             return nonfairTryAcquire(acquires);
         }
    

    nonfairTryAcquire(acquires)

         /**
          * 执行非公平的 tryLock。 tryAcquire 在子类中实现,但两者都需要对 trylock 方法进行非公平尝试。
          */
         final boolean nonfairTryAcquire(int acquires) {
             final Thread current = Thread.currentThread();
             int c = getState();
             if (c == 0) {
                 if (compareAndSetState(0, acquires)) {
                     setExclusiveOwnerThread(current);
                     return true;
                 }
             }
             else if (current == getExclusiveOwnerThread()) {
                 int nextc = c + acquires;
                 if (nextc < 0) // overflow
                     throw new Error("Maximum lock count exceeded");
                 setState(nextc);
                 return true;
             }
             return false;
         }
    

    addWaiter(Node.EXCLUSIVE)

     /**
      * 为当前线程和给定节点创建和排队节点
      *
      * @param mode Node.EXCLUSIVE 用于独占,Node.SHARED 用于共享
      * @return 新节点
      */
     private Node addWaiter(Node mode) {
         Node node = new Node(Thread.currentThread(), mode);
         // Try the fast path of enq; backup to full enq on failure
         Node pred = tail;
         if (pred != null) {
             node.prev = pred;
             if (compareAndSetTail(pred, node)) {
                 pred.next = node;
                 return node;
             }
         }
         enq(node);
         return node;
     }
    

    image.png

    enq(node);

     /**
      * 将节点插入队列,必要时进行初始化。 见上图。
      * @param node 要插入的节点
      * @return 节点的前任
      */
     private Node enq(final Node node) {
         for (;;) {
             Node t = tail;
             if (t == null) { // Must initialize
                 if (compareAndSetHead(new Node()))
                     tail = head;
             } else {
                 node.prev = t;
                 if (compareAndSetTail(t, node)) {
                     t.next = node;
                     return t;
                 }
             }
         }
     }
    

    双向链表中,第一个节点为虚节点(也叫哨兵节点),其实并不存储任何信息,只是占位。真正的第一个有数据的节点,是从第二个节点开始的。

  4. 第一次循环

image.png

  1. 第二次循环

image.png

acquireQueued(addWaiter(Node.EXCLUSIVE), arg)


    /**
     * 以独占不间断模式获取已在队列中的线程。 由条件等待方法以及获取使用。
     *
     * @param node 节点
     * @param arg  acquire 参数
     * @return 如果在等待时中断,则为true
     */
    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);
        }
    }
  1. tryAcquire(arg):再次抢占
  2. 抢占失败进入 shouldParkAfterFailedAcquire 和 parkAndCheckInterrupt 方法中

    shouldParkAfterFailedAcquire

     /**
      * 检查和更新未能获取的节点的状态。 如果线程应该阻塞,则返回 true。 
      * 这是所有获取循环中的主要信号控制。 要求 pred == node.prev。
      *
      * @param pred 节点的前任持有状态
      * @param node 节点
      * @return 如果线程应该阻塞,则为true
      */
     private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
         // 获取前驱节点的状态
         int ws = pred.waitStatus;
         if (ws == Node.SIGNAL)
             /*
              * 如果是 SIGNAL 状态,即等待被占用的资源释放,直接返回 teue
              * 准备继续调用 parkAndCheckInterrupt 方法
              */
             return true;
         if (ws > 0) {
             /*
              * ws > 0 说明是 CANCELLED 状态,
              * 循环判断前驱节点的前驱节点是否也为 CANCELLED 状态,忽略改状态的节点,重新链接队列
              */
             do {
                 node.prev = pred = pred.prev;
             } while (pred.waitStatus > 0);
             pred.next = node;
         } else {
             /*
              * 将当前节点的前驱节点设置为 SIGNAL 状态,用于后续唤醒操作
              * 吹个逼甘晓艺第一次执行到在这返回为 false,还会进行外层第二次循环,最终从第 17 行返回
              */
             compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
         }
         return false;
     }
    
    如果前驱节点的 waitStatus 是 SIGNAL状态,即 shouldParkAfterFailedAcquire 方法会返回 true 程序会继续向下执行 parkAndCheckInterrupt 方法,用于将当前线程挂起
    image.png

    parkAndCheckInterrupt

     /**
      * park 然后检查是否中断的便捷方法
      *
      * @return 如果被中断则为true
      */
     private final boolean parkAndCheckInterrupt() {
         // 线程挂起,程序不会继续向下执行
         LockSupport.park(this);
         // 根据 park 方法 API 描述,程序再下述三种情况会继续向下执行
         // 1. 被 unpark
         // 2. 被中断(interrupt)
         // 3. 其他不合逻辑的返回才会继续向下执行
         // 因上述三种情况程序执行至此,返回当前线程的中断状态,并清空中断状态
         // 如果由于被中断,该方法会返回 true
         return Thread.interrupted();
     }
    

unlock

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

sync.release(1);


    /**
     * 以独占模式发布。 如果tryRelease返回 true,则通过解除阻塞一个或多个线程tryRelease实现。 此方法可用于实现方法Lock.unlock 。
     *
     * @param arg release 参数。 这个值被传递给tryRelease但不会被中断并且可以代表任何你喜欢的东西。
     * @return tryRelease返回的值
     */
    public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

tryRelease(arg)

        protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }

image.png

unparkSuccessor(h)

    /**
     * 唤醒节点的后继节点(如果存在)。
     *
     * @param node 节点
     */
    private void unparkSuccessor(Node node) {
        /*
         * 如果状态是消极的(即,可能需要信号),试着在预期信号时进行清除。这是OK的,如果这失败或状态改变了等待线程。
         */
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);

        /*
         * unpark的线程保存在后续节点中,后续节点通常就是下一个节点。但如果取消或明显为空,则从tail往回遍历以找到实际的未取消的后续。
         */
        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);
    }

image.png