知识图谱整理之Java基础AbstractQueuedSynchronizer

AbstractQueuedSynchronizer介绍

说起这个类,或者说说起这个别名AQS,大家都不会陌生,是一个抽象队列同步器。但是具体内部是如何实现,可能有些人不太了解,今天就来进入这个抽象类的源码。


AbstractQueuedSynchronizer内部数据结构

AQS是一个队列同步器,那必不可少的,肯定存在队列的数据结构,而这是内部实现的,我们来看下这个内部类:

static final class Node {

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;
        /**  信号位,存储之前的CANCELLED、SIGNAL 、CONDITION、 PROPAGATE等*/
		volatile int waitStatus;
		volatile Node prev;
		volatile Node next;
		 /**  参与竞争的线程 */
		volatile Thread thread;
		
		Node nextWaiter;
		final boolean isShared() {
            return nextWaiter == SHARED;
        }

        /**
         * Returns previous node, or throws NullPointerException if null.
         * Use when predecessor cannot be null.  The null check could
         * be elided, but is present to help the VM.
         *
         * @return the predecessor of this node
         */
        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;
        }
}

  • 这里的结构很清晰,主要的难点还是在于关于waitStatus的标识含义
  • CANCELLED代表当前节点已被取消,可以直接跳过
  • SIGNAL代表用来通知下一个节点
  • CONDITION代表当前节点Node在等待队列中,在等待某个条件而被阻塞
  • PROPAGATE只用在共享模式下,表示当前场景下后续的acquireShared能够得以执行

AbstractQueuedSynchronizer的主要方法

主要包含acquire独占方式争抢锁和release释放锁。

acquire方法

先来看源码:

    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
  • 这段代码啥意思呢?我们先来讲tryAcquire方法,这个是用来尝试获取锁的,具体实现是由子类完成的,protected boolean tryAcquire(int arg) { throw new UnsupportedOperationException(); }这里实现是抛出错误。我们可以理解为竞争到锁了就返回true,反之为false;
  • 再来看&&含义,这个是要在前半部分判断成功情况,即没有获取到锁时,在运行下面条件
  • 我们先来看addWaiter方法,源码后面再说,功能是在当前的实例AQS队列上的尾部添加一个当前线程的以独占模式运行的Node节点
  • 再调用了acquireQueued方法,源码稍后分析,功能是判断竞争锁,如果失败则挂起当前线程
  • 最关键的独有领悟,我自己领悟的,关于selfInterrupt这个方法在这有什么用。在acquireQueued过程中的parkAndCheckInterrupt中会调用Thread.interrupted(),这里会吃掉一个线程中断的信号,所以在外部通过这种方式来进行传递。卧槽,这设计,牛逼,之前一直没反应过来。

下面开始解析上面所关联的方法源码分析,首先是addWaiter源码:

addWaiter源码
    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;
    }
  • 这段代码就比较的简单了,就是队列添加尾结点,不过这里如果不存在头结点,会使用enq方法,进行创建一个虚拟头节点,再做插入尾结点操作。enq源码也比较简单,我就不多讲了。
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);
        }
    }
  • 这个方法第一是判断是否是真正意义上的头结点,如果是则获取到锁。
  • 第二个是如果获取失败,则改变前面node节点的waitStatus的值为SIGNAL,这里可以看到前一个节点的waitStatus值是用来标识后一个节点的。
  • 如果标识成功,则调用parkAndCheckInterrupt中的LockSupport.park(this);来阻塞当前线程。后面的Thread.interrupted()的设计之前说了,主要用来传递这个信号量。

release方法源码

    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方法是让子类来实现的
  • 如果释放成功,则判断当前实例的head节点是否不为null,并且waitStatus不为0,说明队列中存在着信号量,我们之后来看下unparkSuccessor方法。
unparkSuccessor源码分析
    private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);

        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
        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);
    }
  • 先把head的信号量改成0,之后就是寻找从head节点开始之后的waitStatus小于0的节点,并通过LockSupport.unpark(s.thread);解除线程挂起状态
  • 这里的查询方式有点特出,会判断如果head的下一个节点不满足的话,会从tail尾结点向上查找到距离head最近的满足节点

#今日总结

关于AbstractQueuedSynchronizer的理解我感觉到目前有了进一步的加深,哈哈,太爽啦,下面分享一下我的知识图谱:
知识图谱

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值