1、案例
以CountDownLatch案例分析共享锁
简单理解:
初始化共享状态 state=5
调用countDown就是将state的值减1,直到减到0为止
当state的值为0时,则会唤醒头结点的后继节点
当state的是不为0时,不做任何处理
调用await时,如果state!=0,创建Node并加入到队列末尾,阻塞
如果state=0,则继续向下执行
import java.util.concurrent.CountDownLatch;
public class MyCountDownLatch {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
Thread[] threads = new Thread[5];
for (int i=0; i<5; i++) {
Thread thread = new Thread(() -> {
System.out.println("执行:");
countDownLatch.countDown();
}, "线程" + i);
threads[i]=thread;
}
for (Thread thread : threads) {
thread.start();
}
System.out.println("等待......");
// 等待上面5个线程执行完毕
countDownLatch.await();
System.out.println("等待:向下执行");
}
}
2、源码分析
2.1、设置共享数量
CountDownLatch countDownLatch = new CountDownLatch(5);
共享state=5
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
Sync(int count) {
// 共享状态state=5
setState(count);
}
2.2、阻塞等待countDownLatch.await()
1、判断state是否等于0,等于0表示可以继续向下执行
2、不等于0,则需要创建Node节点加入到同步队列队尾,阻塞等待唤醒
public void await() throws InterruptedException {
// 获取共享锁
sync.acquireSharedInterruptibly(1);
}
2.2.1、acquireSharedInterruptibly
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
// 响应中断
if (Thread.interrupted())
throw new InterruptedException();
// state是否等于0,是1 否则-1
if (tryAcquireShared(arg) < 0)
// 加入同步队列,阻塞等待
doAcquireSharedInterruptibly(arg);
}
2.2.2、doAcquireSharedInterruptibly加入到同步队列
/**
* 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) {
// 获取共享锁 state=0 ? 1 : -1
int r = tryAcquireShared(arg);
// 获取锁成功
if (r >= 0) {
// 将当前节点设为头节点,并根据情况传播唤醒, 共享锁的唤醒是由刚刚抢到锁的线程来传递的,形成多米诺骨牌
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
// shouldParkAfterFailedAcquire当前驱不是头节点,或者抢锁失败后,检查是否可以 park阻塞
// parkAndCheckInterrupt阻塞线程
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
2.2.3、setHeadAndPropagate
设置成头结点和传播
出队:将当前节点变成新的哨兵节点thread 置为 null,prev 置为 null。此时当前线程已经持有了共享锁。
传播:唤醒后驱节点
/**
* 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())
// 唤醒后驱节点,这块跟调用countDown()线程唤醒后驱节点是同一个方法
doReleaseShared();
}
}
2.3、counDown
每次调用就是将state的值减1
当state=0的时候,唤醒头结点,继续向下执行
public void countDown() {
// 共享状态减1
sync.releaseShared(1);
}
2.3.1、releaseShared
public final boolean releaseShared(int arg) {
// 释放锁, state=0返回true 否则false
if (tryReleaseShared(arg)) {
// 唤醒后驱节点
doReleaseShared();
return true;
}
return false;
}
// 自旋CAS减1,并发保证安全
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
2.3.2、doReleaseShared
职责:在共享锁被释放的时,唤醒等待队列中的后继节点,并确保唤醒操作能够继续传播,从而让多个等待线程能够依次获得锁
两阶段:
第一个阶段:唤醒后继节点(SIGNAL (-1) → 0)
第二个阶段:填补漏洞(0 → PROPAGATE (-3))
/**
* 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) {
// Node.SIGNAL表示需要唤醒后驱节点,0表示已经唤醒后驱节点
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.3.3、unparkSuccessor
唤醒后驱节点:
/**
* 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);
}