关于java:AbstractQueuedSynchronizer那些事儿四-共享模式下的acquireShared

51次阅读

共计 835 个字符,预计需要花费 3 分钟才能阅读完成。

概述

上文剖析了独占模式下的 acquire 实现,本章剖析一下共享模式下的 acquireShared 实现

acquireShared

每个线程都会尝试去获取共享锁,只有获取失败的才会进入 doAcquireShared 办法

  public final void acquireShared(int arg) {if (tryAcquireShared(arg) < 0)
            doAcquireShared(arg);
    }

doAcquireShared

这里共享锁与独占锁的实现相似
首先,也是判断以后节点是否是 head 节点的无效后继节点,如果是的话,以后节点就回去尝试获取一次共享锁,如果获取胜利就调用 setHeadAndPropagate 持续流传,如果不是 head 节点的无效后继节点,就判断以后节点是否应该阻塞,剩下的逻辑与 acquire 相似就不再剖析,重点关注一下 setHeadAndPropagate 的实现

private void doAcquireShared(int arg) {final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {final Node p = node.predecessor();
                if (p == head) {int r = tryAcquireShared(arg);
                    if (r >= 0) {setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        if (interrupted)
                            selfInterrupt();
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {if (failed)
                cancelAcquire(node);
        }

setHeadAndPropagate

正文完
 0