该方法在共享模式以不响应中断的方式阻塞等待获取锁,实现如下:
1、将当前线程封装成节点入队;
2、在死循环中调用park方法。第一次循环(自旋、acquire loop),或者被唤醒从park方法返回后,会判断前驱节点是否是头节点,以及调用tryAcquire()方法是否返回true,如果这2个条件都为真,由当前节点自己设置为头节点,并将后继节点唤醒,然后return;退出死循环。如果这2个条件不满足,会继续调用park方法阻塞等待。
3、在第二步中,被唤醒从park方法返回后,有一个额外操作就是会判断线程的中断状态,如果中断状态为true,仅仅是设置中断标志位interrupted,不抛出中断异常。
4、在第二步中,在判断那2个条件不满足,和调用park方法阻塞等待之间,还有一个操作就是判断在获取失败后是否应该调用park方法阻塞等待。即shouldParkAfterFailedAcquire方法。在acquire loop中会不断调用该方法retry,使该方法最终总是趋向于返回true。
/**
* Acquires in shared uninterruptible mode.
* @param arg the acquire argument
*/
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) && //获取失败后判断是否应该park阻塞等待
parkAndCheckInterrupt()) //调用park方法阻塞等待,park方法返回后判断是否中断
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
该方法在共享模式以响应中断的方式阻塞获取锁。实现逻辑与doAcquireShared方法是基本相同的。不同的是在从park方法返回后,如果判断线程的中断状态为true,会抛出中断异常。
/**
* Acquires in shared interruptible mode.
* @param arg the acquire argument
*/
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
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);
}
}
该方法在当前节点获取失败时判断是否应该使线程阻塞等待。它会检查和更新前驱结点的状态。在acquire loop中会不断调用该方法retry,使最终总是趋向于返回true:
1、刚入队的节点,他们的waitStatus都是int数据类型的初始值0。
2、对于刚入队的节点,它的前驱节点的waitStatus,要么是0,要么是propagate,要么是cancelled。如果前驱节点的waitStatus是0,在第一次acquire loop中,会使用cas将前驱节点的waitStatus设置为SIGNAL。如果前驱节点的waitStatus是propagate,说明该前驱节点是head节点,在第一次acquire loop中,会使用cas将前驱节点的waitStatus设置为SIGNAL。如果前驱节点的waitStatus是cancelled,会从后遍历直至找到有效的前驱节点。虽然在第一次acquire loop中调用shouldParkAfterFailAcquire方法,它的返回值是false,但是在多次acquire loop后,前驱节点的waitStatus总为SIGNAL,该方法的返回值总是true。
/**
* Checks and updates status for a node that failed to acquire.
* Returns true if thread should block. This is the main signal
* control in all acquire loops. Requires that pred == node.prev.
*
* @param pred node's predecessor holding status
* @param node the node
* @return {@code true} if thread should block
*/
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
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 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.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
调用park方法阻塞等待,park方法返回后判断是否中断
/**
* Convenience method to park and then check if interrupted
*
* @return {@code true} if interrupted
*/
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
将当前节点设置为头节点,并将后继节点唤醒,头节点的waitStatus设为propagate。
/**
* Sets head of queue, and checks if successor may be waiting
* in shared mode, if so propagating if either propagate > 0 or
* PROPAGATE status was set.
*
* @param node the node
* @param propagate the return value from a tryAcquireShared
*/
private void setHeadAndPropagate(Node node, int propagate) {
Node h = head; // Record old head for check below
setHead(node);
/*
* Try to signal next queued node if:
* Propagation was indicated by caller,
* or was recorded (as h.waitStatus either before
* or after setHead) by a previous operation
* (note: this uses sign-check of waitStatus because
* PROPAGATE status may transition to SIGNAL.)
* and
* The next node is waiting in shared mode,
* or we don't know, because it appears null
*
* The conservatism in both of these checks may cause
* unnecessary wake-ups, but only when there are multiple
* racing acquires/releases, so most need signals now or soon
* anyway.
*/
if (propagate > 0 || h == null || h.waitStatus < 0 ||
(h = head) == null || h.waitStatus < 0) {
Node s = node.next;
if (s == null || s.isShared())
doReleaseShared(); //将后继节点唤醒,头节点的waitStatus设为propagate
}
}
将后继节点唤醒,头节点的waitStatus设为propagate。
在死循环内:
1、获取head节点的waitStatus;
2、如果head节点的waitStatus为SIGNAL,通过cas将head节点的waitStatus改为0,必须确保cas执行成功,否则通过新一轮循环,再次执行cas操作直至成功为止;(死循环与cas构成自旋锁保证cas执行成功)
3、如果第二步执行成功,调用unparkSuccessor方法唤醒后继节点;
4、第三步执行完成后,开始新一轮的循环,判断如果head节点的waitStatus为0,通过cas将head节点的waitStatus改为propagate,必须确保cas执行成功,否则通过新一轮循环,再次执行cas操作直至成功为止;(死循环与cas构成自旋锁保证cas执行成功)
由此可见,head节点的waitStatus为SIGNAL时,通过两步改为propagate:
compareAndSetWaitStatus(h, Node.SIGNAL, 0)
compareAndSetWaitStatus(h, 0, Node.PROPAGATE)
为什么要经过两步,不直接把SIGNAL改为propagate呢?原因在unparkSuccessor方法。如果直接把SIGNAL改为propagate,则在unparkSuccessor方法里又会被设置为0。
5、在第四步完成后,判断当前head节点是否发生改变,如果没有发生改变,break退出死循环。在第三步唤醒后继节点后,后继节点(所在的线程)会将自己设置为头节点,此时head节点就会发生改变,对新head节点继续执行循环,从而实现release propagate。有细心的网友可能就发现了,新head节点也会调用到doReleaseShared方法,这样会存在多个线程同时调用doReleaseShared方法,执行死循环里的逻辑。是的,代码注释也说明了:
Ensure that a release propagates, even if there are other in-progress acquires/releases.
/**
* Release action for shared mode -- signals successor and ensures
* propagation. (Note: For exclusive mode, release just amounts
* to calling unparkSuccessor of head if it needs signal.)
*/
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.
*/
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;
}
}
如果节点的waitStatus为负,通过cas设置为0;找到有效的后继节点,调用unpark方法
/**
* Wakes up node's successor, if one exists.
*
* @param node the node
*/
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);
}