独占资源
获取独占
流程
-
尝试获取资源,成功则直接返回,失败则进入队列再次尝试获取资源,
-
成功则修改头节点为自己的节点,旧头节点移出队列。失败则阻塞之前修改前驱快照ws再次尝试获取资源。
-
成功则修改头节点为自己节点,旧头节点移出队列。失败则阻塞。
释放独占
流程:
- 尝试释放独占资源,若成功,则唤醒头节点的后继(如果存在需要唤醒的后继)。若失败则返回false。
多线程下队列状态分析
假设线程A,B先后尝试获取锁,线程进入队列的时候一定都是插入队列尾部。(由CAS tail保证) 此时队列状态有下图可能性
- head-> B (tail 是B) (线程A还未进入队列就获取成功了)
- head-> A -> B (线程A,B第一步都失败,tail = B )
- head-> B -> A (线程A,B第一步都失败, tail = A)
队列中的节点,只有head节点的后继才可以进行尝试获取资源操作,(当然,这里的head节点并不保证是最新值。)假设线程A为head节点后继(即状态2所示) 线程A获取资源成功后,队列如下图所示:
- A->B (此时,head = A, tail = B )。 如果此时进来了线程C,若A没抢过C。则队列状态同2。若C没抢过A,则队列状态如下图
- A->B->C (此时head = A, tail = C)。
多线程下运行状态分析
- 存在线程A释放锁了的时候,线程B获取锁失败还不在队列中的情况 但线程B会在进入队列时再次尝试获取资源。
- 存在线程A释放了锁的时候,线程B进入了队列还没有再次获取资源。线程A释放锁。线程B获取资源成功。
- 存在线程A释放了锁的时候,线程B进入了队列获取资源再次失败但还没有修改ws导致线程A无需唤醒B直接释放。但线程B会在ws修改后再次尝试获取资源。
- 存在线程A释放了锁的时候,线程B进入了队列获取资源再次失败但还没有修改ws,线程B会在ws修改后再次尝试获取资源。线程B获取资源成功后,线程A唤醒后继节点(即B带着unpark -1 状态出来)。
- 存在线程A释放了锁的时候,线程B进入了队列获取资源再次失败,修改ws后阻塞,线程A释放锁。线程B会被唤醒
- 存在线程A释放了锁的时候,线程B进入了队列获取资源再次失败,修改ws后在线程A释放锁后阻塞,线程B依然会被唤醒。(原因在于unpark,park方法语义) 以上只考虑了2个线程的情况。对于多个线程情况,只需要将线程B换为队列中head后继节点对应的线程即可。可以看到。当一个线程释放锁的时候,队列head的后继节点一定是可以获取到锁的。
```java
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) //acquireQueued返回的是中断标志。当该方法返回时说明资源获取成功了。否则阻塞在该方法上
selfInterrupt();
}
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) { //队列中头节点才可以尝试获取资源。注意这里的head一定是最新值!因为只有队列中的节点获取资源才可以改变head,而只有队列中head后继才拥有获取资源的机会。
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
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;
}
这里语句1 中的h是head节点快照(即非最新值,存在数据竞争的情况)。
如果h == null 说明此时有队列中的head后继获取资源成功并修改了head同时旧head被GC回收。
如果h.ws == 0说明不存在需要唤醒的后继,这里ws具有可见性的保证。
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0) //1
unparkSuccessor(h);
return true;
}
return false;
}
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);
}