最近有点着迷,countDownLatch还是比较简单的。也是Doug Lea之笔,其实思想都差不多。
构造器方法
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
看看他的aqs
private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L;
Sync(int count) {
setState(count);
}
int getCount() {
return getState();
}
//先盲猜一下 await方法,肯定会调这个方法。
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
//盲猜countDown方法会调这个方法。往下看
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;
}
}
}
await方法
本来先读的countDown方法,后面发现得先写这个,因为其实await要阻塞,park,而countDown相当于去unpark。
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
acquireSharedInterruptibly 方法
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
//说明await方法是可以被打断的
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
tryAcquireShared 方法
说明之前的猜想正确,如果 == 0 await方法直接返回,不等于0的话,
doAcquireSharedInterruptibly就是阻塞他。
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
doAcquireSharedInterruptibly方法
之前读写锁都写过了不做过多说明。只写一下unpark之后的操作。
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
//unpark之后再次进入循环,这个时候p == head成立
if (p == head) {
//此时state == 0,然后r=1,进入代码块中return
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);
}
}
countDown方法
public void countDown() {
sync.releaseShared(1);
}
releaseShared方法
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
tryReleaseShared 方法
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
//如果这个总数 == 0,直接返回false
if (c == 0)
return false;
// cas去减一。
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
doReleaseShared 方法
aqs的方法,首先当state == 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.
*/
for (;;) {
Node h = head;
//如果aqs队列被初始化了
if (h != null && h != tail) {
int ws = h.waitStatus;
//如果ws == -1,说明后面还有人排队
if (ws == Node.SIGNAL) {
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
//这个方法就是唤醒他的下一个节点,读写锁源码解读过
unparkSuccessor(h);
}
//如果ws == 0,说明后面没人排队直接把这个改成-3。
//下一轮循环就返回了
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
总结
总的来说,CountDownLatch比ReentrantLock ReentrantReadWriteLock简单很多,没那么绕,其实原理也差不多,就是入队出队,unpark,park,cas乐观锁去改值。