【线程安全】2.2 锁--AQS(AbstractQueuedSynchronizer)

AbstractQueuedSynchronizer,它是阻塞式锁和相关同步器的框架。

AbstractQueuedSynchronizer 的结构和 Monitor 对象的结构有些类似,都有只有所得线程、阻塞队列等。

1. 属性与结构

1.1 几个重要的属性

public abstract class AbstractQueuedSynchronizer
    extends AbstractOwnableSynchronizer
    implements java.io.Serializable {
    /**
     * Head of the wait queue, lazily initialized.  Except for
     * initialization, it is modified only via method setHead.  Note:
     * If head exists, its waitStatus is guaranteed not to be
     * CANCELLED.
     */
    private transient volatile Node head;

    /**
     * Tail of the wait queue, lazily initialized.  Modified only via
     * method enq to add new wait node.
     */
    private transient volatile Node tail;

    /**
     * The synchronization state.
     */
    private volatile int state;
public abstract class AbstractOwnableSynchronizer
    implements java.io.Serializable {
    /**
     * The current owner of exclusive mode synchronization.
     */
    private transient Thread exclusiveOwnerThread;

加上从 AbstractOwnableSynchronizer 继承来的属性,这里重点关注的是以下四个属性:

state: 正整数,表示锁的状态,0 表示没有被占用,1 表示被占用,大于 1 则表示重入的次数。

head: Node 类型的对象,阻塞队列的头结点,头结点是无意义的,只是用来连接,也被称为哑元或哨兵

tail: Node 类型的对象,阻塞队列的尾结点

exclusiveOwnerThread: 当前持有锁的线程

1.2 内部类

  1. 双向阻塞队列的节点类
static final class Node {
        /** Marker to indicate a node is waiting in shared mode */
        static final Node SHARED = new Node();
        /** Marker to indicate a node is waiting in exclusive mode */
        static final Node EXCLUSIVE = null;

        /** waitStatus value to indicate thread has cancelled */
        static final int CANCELLED =  1;
        /** waitStatus value to indicate successor's thread needs unparking */
        static final int SIGNAL    = -1;
        /** waitStatus value to indicate thread is waiting on condition */
        static final int CONDITION = -2;
        /**
         * waitStatus value to indicate the next acquireShared should
         * unconditionally propagate
         */
        static final int PROPAGATE = -3;

        /**
         * Status field, taking on only the values:
         *   SIGNAL:     The successor of this node is (or will soon be)
         *               blocked (via park), so the current node must
         *               unpark its successor when it releases or
         *               cancels. To avoid races, acquire methods must
         *               first indicate they need a signal,
         *               then retry the atomic acquire, and then,
         *               on failure, block.
         *   CANCELLED:  This node is cancelled due to timeout or interrupt.
         *               Nodes never leave this state. In particular,
         *               a thread with cancelled node never again blocks.
         *   CONDITION:  This node is currently on a condition queue.
         *               It will not be used as a sync queue node
         *               until transferred, at which time the status
         *               will be set to 0. (Use of this value here has
         *               nothing to do with the other uses of the
         *               field, but simplifies mechanics.)
         *   PROPAGATE:  A releaseShared should be propagated to other
         *               nodes. This is set (for head node only) in
         *               doReleaseShared to ensure propagation
         *               continues, even if other operations have
         *               since intervened.
         *   0:          None of the above
         *
         * The values are arranged numerically to simplify use.
         * Non-negative values mean that a node doesn't need to
         * signal. So, most code doesn't need to check for particular
         * values, just for sign.
         *
         * The field is initialized to 0 for normal sync nodes, and
         * CONDITION for condition nodes.  It is modified using CAS
         * (or when possible, unconditional volatile writes).
         */
        volatile int waitStatus;

        volatile Node prev;

        volatile Node next;

        volatile Thread thread;

        Node nextWaiter;

Node 是链表(类似于 monitor 的 entryList)的节点类,上面提到的 head、tail 都是这个类型对象。每个阻塞的线程都用 Node 封装起来构成一个链表节点加在队尾。

除了前驱节点、后继节点,还有以下几个属性:
waitStatus:线程的等待状态
thread:用于存储阻塞的线程
SHARED:new Node(),静态常量,代表共享锁
EXCLUSIVE:值为 null,是静态常量,代表排它锁
nextWaiter:下一个节点,ConditionObject 专用。prev、next 是 AQS 阻塞队列专用。

AQS 阻塞队列是双向链表(prev、next),ConditionObject 中的队列是单向链表(nextWaiter)

其中 waitStatus 的几种状态:
CANCELLED:值为 1,代表取消等待,除了这个状态,其他几个都是有效状态
SIGNAL: -1,等待被唤醒
CONDITION:-2,等待被条件变量唤醒
PROPAGATE:-3,没看懂....

只有 ConditionObject 中 waitStatus 才可能是 CONDITION

  1. 条件变量类
    public class ConditionObject implements Condition, java.io.Serializable {
        /** First node of condition queue. */
        private transient Node firstWaiter;
        /** Last node of condition queue. */
        private transient Node lastWaiter;

条件变量实际也是一个 Node 组成的链表,这里没有哑元,都是有效节点,而且这个链表是单向的,因为他用的是nextWaiter属性。

1.3 加锁、解锁方法没有具体实现

对于加锁、解锁方法,AQS 并没有具体实现,而是留给子类去实现。

2. 加锁、就锁过程

因为 AQS 是抽象类,加锁、解锁的方法没有具体实现,而是留给子类去实现,所以这里只是说一下大概思想和流程。

加锁成功
通过对 state 属性 CAS 尝试将其从 0 改为 1,如果修改成功,就进一步把 exclusiveOwnerThread 设置为当前线程。这样就加锁成功了。

锁重入
CAS 修改 state 的时候失败的话,会先判断 exclusiveOwnerThread == Thread.currentThread() 是否为真,如果是真,就说明是锁重入,state++ 即可。

加锁失败
和 monitor 类似,如果加锁失败而且不是锁重入的情况,就需要让线程进入阻塞队列,将线程封装在 Node 对象中,添加到队尾。

解锁
解锁,就是每释放一次锁,就 state--,减到 0,说明已经是最初加锁的地方了,将 exclusiveOwnerThread 设置为 null。

AQS 只是给出抽象的框架,具体是公平还是非公平,共享还是排他等等一些细节仍需要子类去具体实现。

AQS 对属性的 CAS 操作都有实现,基于 Unsafe,阻塞、唤醒线程用的是 LockSupport.park(t), LockSupport.unPark(),实际上也是 基于Unsafe 类

3. 条件变量

3.1 await 阻塞

        public final void await() throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
            Node node = addConditionWaiter();
            int savedState = fullyRelease(node);
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {
                LockSupport.park(this);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null) // clean up if cancelled
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
        }

addConditionWaiter 方法就是将阻塞线程用 Node 封装一下,加到队尾。

        private Node addConditionWaiter() {
            Node t = lastWaiter;
            // If lastWaiter is cancelled, clean out.
            if (t != null && t.waitStatus != Node.CONDITION) {
                unlinkCancelledWaiters();
                t = lastWaiter;
            }
            Node node = new Node(Thread.currentThread(), Node.CONDITION);
            if (t == null)
                firstWaiter = node;
            else
                t.nextWaiter = node;
            lastWaiter = node;
            return node;
        }

添加到条件变量队尾之后,因为线程还未阻塞,有可能在此过程中获取到了锁,然而开发者调用 await 是为了阻塞线程,并等待 signal 唤醒,并不希望它此时得到锁,所以调用 fullyRelease 将锁释放(如果得到了锁)。

    final int fullyRelease(Node node) {
        boolean failed = true;
        try {
            int savedState = getState();
            if (release(savedState)) {
                failed = false;
                return savedState;
            } else {
                throw new IllegalMonitorStateException();
            }
        } finally {
            if (failed)
                node.waitStatus = Node.CANCELLED;
        }
    }

当前节点已经加入到 ConditionObject 的单向队列中,但是是否加到了 AQS 阻塞队列需要用 isOnSyncQueue 方法来判断。

    final boolean isOnSyncQueue(Node node) {
        if (node.waitStatus == Node.CONDITION || node.prev == null)
            return false;
        if (node.next != null) // If has successor, it must be on queue
            return true;
        /*
         * node.prev can be non-null, but not yet on queue because
         * the CAS to place it on queue can fail. So we have to
         * traverse from tail to make sure it actually made it.  It
         * will always be near the tail in calls to this method, and
         * unless the CAS failed (which is unlikely), it will be
         * there, so we hardly ever traverse much.
         */
        return findNodeFromTail(node);
    }

如果还没有被添加到 AQS 队列中,就将线程 park。如果能从 while (!isOnSyncQueue(node)) 循环中出来,说明被加载到了 AQS 阻塞队列中了,或者是 park 被唤醒了。

3.2 signal 唤醒

如果线程持有锁,那 signal 方法会报错,否则就唤醒队列中的第一个节点。

        public final void signal() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            Node first = firstWaiter;
            if (first != null)
                doSignal(first);
        }
        private void doSignal(Node first) {
            do {
                //将头结点更换为头结点的后继节点
                if ( (firstWaiter = first.nextWaiter) == null)
                    lastWaiter = null;
                first.nextWaiter = null;
            } while (!transferForSignal(first) &&
                     (first = firstWaiter) != null);
        }

尝试释放

    final boolean transferForSignal(Node node) {
        /*
         * If cannot change waitStatus, the node has been cancelled.
         */
        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
            return false;

        /*
         * 将从条将变量取出的头结点,添加到 AQS 的尾结点中
         */
        Node p = enq(node);
        int ws = p.waitStatus;
        // 判断 waitStatus,如果大于零或者,修改为 SIGNAL 失败,就 unpark 该节点退出阻塞
        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
            LockSupport.unpark(node.thread);
        return true;
    }

线程是阻塞在上面的 await 方法中,在 transferForSignal 将线程 unpark 之后,就会执行 await 后面的代码,大致就是清除节点之类的。之后就可以正常实行业务逻辑了。

还有一种情况,修改没有进入到 unpark 的逻辑之中,这种的就要排队等着了。。。等它的前驱节点唤醒它。

你可能感兴趣的:(【线程安全】2.2 锁--AQS(AbstractQueuedSynchronizer))