JUC并发包

并发包同步器的核心AQS-深入-加锁

2021-03-25  本文已影响0人  于情于你
AQS API 节点的状态

下面我们借助上面的API图阅读源码

独占模式获取锁acquire,忽略中断
 public final void acquire(int arg) {

        // 尝试获取锁,如果获取不成功,则加入到CLH队列等待,并且中断当前线程
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

 protected boolean tryAcquire(int arg) {
        throw new UnsupportedOperationException();
    }

  private Node addWaiter(Node mode) {
        // 用当前线程创建一个Node,mode=Node.EXCLUSIVE也就是null(独占锁的nextWaiter是null)
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        // 如果CLH队尾是空的,或者CAS把新节点更新成尾结点失败了,则调用完整入队方法enq
        // 否则快速入队
        Node pred = tail;
        if (pred != null) {
            // 新节点的前置结点指向pred(原队尾结点)
            node.prev = pred;
            // 将tail更新成新节点node,但是不会影响局部变量pred,pred还是原队尾结点
            if (compareAndSetTail(pred, node)) {
                // 原队尾结点.next指向新节点
                pred.next = node;
                return node;
            }
        }
        // 完整入队
        enq(node);
        return node;
    }
addWaiter

tryAcquire是需要子类必须重写的方法,如果不重写就会抛出UnsupportedOperationException

独占模式获取锁acquire,响应中断
 public final void acquireInterruptibly(int arg)
            throws InterruptedException {
        // 当前线程被中断,抛出InterruptedException
        if (Thread.interrupted())
            throw new InterruptedException();
       // 如果尝试获取锁失败,那么在可中断模式下获取锁
        if (!tryAcquire(arg))
            doAcquireInterruptibly(arg);
    }

 /**
     * Acquires in exclusive interruptible mode.
     * @param arg the acquire argument
     */
    private void doAcquireInterruptibly(int arg)
        throws InterruptedException {
        // 创建一个和当前线程绑定Node,并加入队尾
        final Node node = addWaiter(Node.EXCLUSIVE);
        boolean failed = true;
        try {
            for (;;) {
                // 获取node的前置节点
                final Node p = node.predecessor();
                // 如果node的前置节点就是头节点了,那么应该拿到资源的线程应该是当前线程,也就是新创建的node
                if (p == head && tryAcquire(arg)) {
                    // 拿到资源后把node设置为head节点,因为这个node拿到资源了,要轮到下一个node了
                    setHead(node);
                   // 把原head节点删除
                    p.next = null; // help GC
                    failed = false;
                    return;
                }
                // 如果拿锁失败,并且需要挂起,那么需要挂起当前线程,并设置中断状态
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            // 没拿到锁取消当前节点拿锁请求
            if (failed)
                cancelAcquire(node);
        }
    }



private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;

        // 如果前一个节点的状态是SIGNAL,返回true,可以将当前线程挂起
        if (ws == Node.SIGNAL)
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;

        // 如果如果前一个节点的状态是CANCELLED,那么循环向前查找取消节点,把取消节点从队列中删除
        if (ws > 0) {
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {

          // 如果是其他状态,那么将前置节点的waitStatus设置成SIGNAL
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }

Q:在shouldParkAfterFailedAcquire中为什么前置节点的状态是SIGNAL了,还要挂起当前线程?
A:节点状态是SIGNAL表示当前节点如果释放锁,可以通知唤醒后面的节点了。当获取锁失败的时候,如果前置节点状态是SIGNAL就表明,可以安全的挂起当前线程,因为前置节点一旦释放锁,会通知唤醒后面的节点。
Q:HEAD节点是干嘛的,为什要有它?
A:HEAD节点表示已经获取到锁的节点(doAcquireInterruptibly方法,setHead),前面说了,SIGNAL表示当前节点如果释放锁,可以通知唤醒后面的节点了。所以所有的线程在休眠之前都要,把前置节点的状态设置成SIGNAL,否则自己永远无法被唤醒。那么第一个节点没有前置节点怎么办呢,那就加一个HEAD。

独占模式获取锁tryAcquireNanos(int arg, long nanosTimeout),响应中断并且带有超时时间
public final boolean tryAcquireNanos(int arg, long nanosTimeout)
            throws InterruptedException {
       // 如果当前线程被中断那么抛出InterruptedException
        if (Thread.interrupted())
            throw new InterruptedException();
        // 直接获取锁,若获取不成功,就进入到带有超时时间的获取锁方法doAcquireNanos
        return tryAcquire(arg) ||
            doAcquireNanos(arg, nanosTimeout);
    }

 private boolean doAcquireNanos(int arg, long nanosTimeout)
            throws InterruptedException {
        // 边界检查
        if (nanosTimeout <= 0L)
            return false;
        // 当前时间+超时时间=过期时间
        final long deadline = System.nanoTime() + nanosTimeout;
        // 新加一个节点
        final Node node = addWaiter(Node.EXCLUSIVE);
        boolean failed = true;
        try {
            for (;;) {
                // 若前置节点是head,说明当前线程可以获取锁了,获取锁成功后,释放原head节点
                // 并且将新加的节点node设置为head
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return true;
                }
                // 循环拿锁中超时检查,若超时返回false
                nanosTimeout = deadline - System.nanoTime();
                if (nanosTimeout <= 0L)
                    return false;
                // 如果当前节点可以被挂起,并且还剩余的时间大于超时时间的阈值1000L的话,挂起当前线程nanosTimeout纳秒
                if (shouldParkAfterFailedAcquire(p, node) &&
                    nanosTimeout > spinForTimeoutThreshold)
                    LockSupport.parkNanos(this, nanosTimeout);
                  // 如果当前线程被中断了,那么抛出InterruptedException
                if (Thread.interrupted())
                    throw new InterruptedException();
            }
        } finally {

            // 没获取到锁,取消节点拿锁请求
            if (failed)
                cancelAcquire(node);
        }
    }

Q:为何循坏拿锁的时候,如果当前节点可以被挂起,并且还剩余的时间大于超时时间的阈值1000L的话,挂起当前线程nanosTimeout纳秒?
A:为了提高响应能力,如果不挂起当前线程的话,在这剩余的超时时间里会占用资源一直循环拿锁,直到超时或者线程被中断为止。挂起当前线程nanosTimeout纳秒,在这期间可以让别的线程先去占资源。

上一篇下一篇

猜你喜欢

热点阅读