AQS 源码解读系列--CountDownLatch 篇

39 篇文章 0 订阅
21 篇文章 0 订阅

CountDownLatch 作为 AQS 中提供的计数器,一般适合用于某个任务的触发需要依赖于一个或多个前置任务的就绪的场景,比如某个数据分析的任务需要依赖于多个文件的解析完成才能进行;适合用于多个任务的同时触发需要依赖于一个或多个前置任务的就绪的场景,典型的就是用作发令枪来模拟并发的场景。本篇我们一起了解其实现原理,由于 CountDownLatch 的实现中,多数方法都在前面介绍重入锁及重入读写锁时涉及到,因此本篇不会详细说明,如有需要,请参考本系列的其他文章进行了解。

1. countDown()

public void countDown() {
    sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
	// 计数器减一,返回计数器的值是否为 0;如果为 0 则唤醒队列中的头节点
    if (tryReleaseShared(arg)) {
        doReleaseShared();
        return true;
    }
    return false;
}

tryReleaseShared()

protected boolean tryReleaseShared(int releases) {
    // Decrement count; signal when transition to zero
    for (;;) {
    	// 初始化 CountDownLatch 时,传入的数值,会设置到 state 中,因此这里根据它判断是否到达 0
        int c = getState();
        if (c == 0)
            return false;
        int nextc = c-1;
        if (compareAndSetState(c, nextc))
            return nextc == 0;
    }
}
private void doReleaseShared() {
    /*
     * Ensure that a release propagates, even if there are other
     * in-progress acquires/releases.  This proceeds in the usual
     * way of trying to unparkSuccessor of head if it needs
     * signal. But if it does not, status is set to PROPAGATE to
     * ensure that upon release, propagation continues.
     * Additionally, we must loop in case a new node is added
     * while we are doing this. Also, unlike other uses of
     * unparkSuccessor, we need to know if CAS to reset status
     * fails, if so rechecking.
     */
    // 将头节点的 waitStatus 由 SIGNAL 置为 PROPAGATE,并唤醒头节点的后继节点
    for (;;) {
        Node h = head;
        if (h != null && h != tail) {
            int ws = h.waitStatus;
            if (ws == Node.SIGNAL) {
                if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                    continue;            // loop to recheck cases
                unparkSuccessor(h);
            }
            else if (ws == 0 &&
                     !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                continue;                // loop on failed CAS
        }
        if (h == head)                   // loop if head changed
            break;
    }
}

2. await()

public void await() throws InterruptedException {
    sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
        throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    // 判断计数器是否到达 0,是则直接返回;否则自旋等待
    if (tryAcquireShared(arg) < 0)
        doAcquireSharedInterruptibly(arg);
}

tryAcquireShared()

protected int tryAcquireShared(int acquires) {
    return (getState() == 0) ? 1 : -1;
}

doAcquireSharedInterruptibly()

private void doAcquireSharedInterruptibly(int arg)
    throws InterruptedException {
    // 将线程构造成 node 节点并入队
    final Node node = addWaiter(Node.SHARED);
    boolean failed = true;
    try {
        for (;;) {
            final Node p = node.predecessor();
            // 前驱节点是头节点,尝试获取
            if (p == head) {
                int r = tryAcquireShared(arg);
                // 获取成功,将当前节点设置成头节点并传播(唤醒后继节点)
                if (r >= 0) {
                    setHeadAndPropagate(node, r);
                    p.next = null; // help GC
                    failed = false;
                    return;
                }
            }
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                throw new InterruptedException();
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值