AQS笔记之独占式获取同步状态

本文详细探讨了AQS的独占式获取同步状态的四种情况:不响应中断、响应中断、超时获取。通过分析acquire、acquireInterruptibly、doAcquireNanos等关键方法,阐述了不同情况下线程的等待、中断响应及超时处理机制。总结了各类获取方式之间的主要区别。
摘要由CSDN通过智能技术生成

导览

跟着函数调用轨迹走一遍。

1、不响应中断

acquire方法


public final void acquire(int arg) {
        if (!tryAcquire(arg) &&//尝试获取同步状态(需重写)
            //获取同步状态失败时进入同步队列并自旋获取同步状态,返回值为此过程中线程是否发生中断
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();//当前线程将自己中断
}

查看addWaiter方法acquireQueued方法
此方法一般被ReentrantLock类的lock方法调用

addWaiter方法

private Node addWaiter(Node mode) {
        Node node = new Node(mode);//将当前线程构造成独占式(EXCLUSIVE)/共享式(SHARED)节点,其中同步状态status默认为0

        for (;;) {
            Node oldTail = tail;
            if (oldTail != null) {
                node.setPrevRelaxed(oldTail);
                if (compareAndSetTail(oldTail, node)) {//将当前节点设置为队尾节点并返回
                    oldTail.next = node;
                    return node;
                }
            } else {//若同步队列还未进行初始化则先初始化(注意:初始化时,头结点中并不存放任何线程)
                initializeSyncQueue();
            }
        }
}

此方法被acquire方法doAcquireNanos方法doAcquireInterruptibly方法调用

acquireQueued方法

final boolean acquireQueued(final Node node, int arg) {//返回当前线程是否被中断
        boolean interrupted = false;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {//当前驱节点为头结点时,尝试获取同步状态
                    /*
                    private void setHead(Node node) {
        				head = node;
        				node.thread = null;
        				node.prev = null;
    				}
                    */
                    setHead(node);
                    p.next = null; // help GC
                    return interrupted;
                }
                //只有在前驱节点等待状态为SIGNAL的情况下才会将自己挂起,因为SIGNAL状态下的节点会在状态改变时唤醒后继节点
                if (shouldParkAfterFailedAcquire(p, node))//尝试获取同步状态失败后,判断当前节点是否应该被挂起(阻塞)
                    interrupted |= parkAndCheckInterrupt();//将当前线程挂起(阻塞),并检查此过程中线程是否被中断
            }
        } catch (Throwable t) {
            cancelAcquire(node);//捕获到异常,则取消获取同步状态,移出同步队列,唤醒后继节点
            if (interrupted)
                selfInterrupt();
            throw t;
        }
}

查看shouldParkAfterFailedAcquire方法parkAndCheckInterrupt方法cancelAcquire方法
此方法被acquire方法调用

shouldParkAfterFailedAcquire方法

/*当且仅当前驱节点为SIGNAL时,返回true,即当前线程可以被挂起(阻塞)*/
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;//获取前驱节点的等待状态
        if (ws == Node.SIGNAL)//SIGNAL表示后继节点的线程处于等待状态
        //注意:处于SIGNAL的的线程在释放同步状态或被取消会通知其后继节点,使后继节点得以运行
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;
        if (ws > 0) {//ws=CANCELLED表示需要从同步队列中取消等待
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
             
            do {//将同步队列中当前线程节点以前取消等待的线程移除(并不一定会将从头结点到当前节点之间取消等待的节点都移除)
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            /* 前驱节点为SIGNAL时才会挂起自己,若为其他状态(0 or PROPAGATE)就不会唤醒当前节点线程
             * waitStatus must be 0 or PROPAGATE.  Indicate that we
             * need a signal, but don't park yet.  Caller will need to
             * retry to make sure it cannot acquire before parking.
             */
            pred.compareAndSetWaitStatus(ws, Node.SIGNAL);//直接前驱节点的等待状态设置为SIGNAL
        }
        return false;
    }

此方法被acquireQueued方法doAcquireNanos方法doAcquireInterruptibly方法调用

parkAndCheckInterrupt方法

private final boolean parkAndCheckInterrupt() {
        LockSupport.park(this);//挂起当前线程
        return Thread.interrupted();//返回当前线程的中断情况
}

查看LockSupport类
此方法被acquireQueued方法doAcquireNanos方法doAcquireInterruptibly方法调用

cancelAcquire方法

private void cancelAcquire(Node node) {
        // Ignore if node doesn't exist
        if (node == null)
            return;

        node.thread = null;

        // Skip cancelled predecessors
        Node pred = node.prev;
        while (pred.waitStatus > 0)//找到距离当前线程节点最近的未被取消等待的前驱线程节点pred
            node.prev = pred = pred.prev;

        // predNext is the apparent node to unsplice. CASes below will
        // fail if not, in which case, we lost race vs another cancel
        // or signal, so no further action is necessary.
        Node predNext = pred.next;

        // Can use unconditional write instead of CAS here.
        // After this atomic step, other Nodes can skip past us.
        // Before, we are free of interference from other threads.
        node.waitStatus = Node.CANCELLED;//将当前线程节点node的等待状态设置为CANCELLED

        // If we are the tail, remove ourselves.
        if (node == tail && compareAndSetTail(node, pred)) {//若当前线程节点node为尾节点则将pred设置为尾节点
            pred.compareAndSetNext(predNext, null);
        } else {
            // If successor needs signal, try to set pred's next-link
            // so it will get one. Otherwise wake it up to propagate.
            int ws;
            //在pred不为头结点且pred及node.next节点不为CANCELLED的情况下,将node.next节点设置为pred的后继节点
            if (pred != head &&
                ((ws = pred.waitStatus) == Node.SIGNAL ||
                 (ws <= 0 && pred.compareAndSetWaitStatus(ws, Node.SIGNAL))) &&
                pred.thread != null) {
                Node next = node.next;
                if (next != null && next.waitStatus <= 0)
                    pred.compareAndSetNext(predNext, next);
            } else {//否则
                unparkSuccessor(node);//唤醒后继节点
            }

            node.next = node; // help GC
        }
    }

查看unparkSuccessor方法
此方法被acquireQueued方法doAcquireNanos方法doAcquireInterruptibly方法调用

release方法

//释放同步状态,若成功则返回true,若失败则返回false
public final boolean release(int arg) {
        if (tryRelease(arg)) {//尝试释放同步状态(修改同步状态),需重写
            Node h = head;
            //当头结点不为空且其等待状态不为0时,唤醒其后继节点
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);//唤醒h的后继节点
            return true;
        }
        return false;
}

注意:在重写tryRelease方法时,当前线程重入同一个锁arg次,那么释放的时候也需要释放arg次,锁才会真正被释放。
查看unparkSuccessor方法
此方法一般被ReentrantLock类的unLock方法调用

unparkSuccessor方法

    /*
    从这个方法并结合acquireQueued方法可以看出,头结点仅仅完成了释放同步状态,并唤醒后继节点。
    头结点在做完这些事情之后其后继节点将开始尝试获取同步状态,并在成功之后将自己设置为头结点并断开与“前”头结点的连接。
    */
    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)//若等待状态<0,则将等待状态修改为0
            node.compareAndSetWaitStatus(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) {//若node.next已经被取消等待状态
            s = null;
            for (Node p = tail; p != node && p != null; p = p.prev)//找到距离node最近的未被取消等待状态的线程节点s
                if (p.waitStatus <= 0)
                    s = p;
        }
        if (s != null)//若s不为null则唤醒s节点中的线程
            LockSupport.unpark(s.thread);
    }

查看LockSupport类
此方法被release方法cancelAcquire方法调用

2、响应中断

acquireInterruptibly方法

public final void acquireInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (!tryAcquire(arg))
            doAcquireInterruptibly(arg);//可响应中断
}

查看doAcquireInterruptibly方法

doAcquireInterruptibly方法

private void doAcquireInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.EXCLUSIVE);
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    return;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())//若在此过程中发生中断则清空中断标志位并抛出中断异常
                    throw new InterruptedException();
            }
        } catch (Throwable t) {
            cancelAcquire(node);
            throw t;
        }
}

查看addWaiter方法shouldParkAfterFailedAcquire方法parkAndCheckInterrupt方法cancelAcquire方法
此方法被acquireInterruptibly方法调用

3、独占式超时获取同步状态

doAcquireNanos方法

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);
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    return true;
                }
                nanosTimeout = deadline - System.nanoTime();
                if (nanosTimeout <= 0L) {//超时取消等待
                    cancelAcquire(node);
                    return false;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    nanosTimeout > SPIN_FOR_TIMEOUT_THRESHOLD)//超时时间≤阈值则快速自旋而不会被阻塞(挂起)
                    LockSupport.parkNanos(this, nanosTimeout);
                if (Thread.interrupted())
                    throw new InterruptedException();
            }
        } catch (Throwable t) {
            cancelAcquire(node);
            throw t;
        }
}

查看addWaiter方法cancelAcquire方法shouldParkAfterFailedAcquire方法
从上面的方法可以看出,

  • 若当前线程获取同步状态失败,则判断是否超时,若没有超时则重新计算超时时间间隔,然后使当前线程等待超时时间间隔(当然,若在等待过程中的超时则自动从LockSupport.parkNanos方法返回),若已经超时则取消等待。
  • 在等待过程中若发生中断会进行响应(抛出InterruptedException异常并取消获取锁)。
  • 在超时时间小于一定的阈值时,将不会进入阻塞状态(被挂起)而是进行快速自旋。原因是:非常短的超时等待无法做到十分精确,如果这是在进行超时等待,反而会使超时从整体上表现的不精确,因此在超时时间非常短的情况下,同步器会无条件快速自旋。

4、总结

不响应中断的获取方式与响应中断的获取方式之间的区别
acquire方法可以看出,不响应中断即线程在未获取到锁而进入同步队列之后在其阻塞(被挂起)的过程中若发生中断(中断标志位置位),线程从parkAndCheckInterrupt方法中被唤醒后仅采用boolean型变量记录此过程发生过中断(中断标志位清零),直到线程被唤醒并获取到锁之后(说明线程发生中断后仍然会等待获取锁)或者抛出其他异常才会调用selfInterrupt()方法将自己中断。
而响应中断的获取方式与前者大致相同,唯一区别在于:从doAcquireInterruptibly方法acquireInterruptibly方法,若线程在同步队列中阻塞期间发生中断,则线程从parkAndCheckInterrupt方法中被唤醒后会抛出InterruptedException异常并取消获取锁。
独占式获取同步状态与独占式超时获取同步状态之间的区别
两者过程相似,仅在同步状态获取失败的处理逻辑上有所不同。acquire方法在未获取到同步状态是,将会使当前线程一直处于等待状态,而doAcquireNanos方法会使当前线程等待一个超时时间,若在超时时间内未获取到同步状态,则会从等待逻辑中自动返回。

返回顶部

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值