publicclassCountDownLatch{/** * Synchronization control For CountDownLatch. * Uses AQS state to represent count. */privatestaticfinalclassSyncextendsAbstractQueuedSynchronizer{privatestaticfinallongserialVersionUID=4982264981922014374L;Sync(intcount){setState(count);}intgetCount(){returngetState();}protectedinttryAcquireShared(intacquires){return(getState()==0)?1:-1;}protectedbooleantryReleaseShared(intreleases){// Decrement count; signal when transition to zerofor(;;){intc=getState();if(c==0)returnfalse;intnextc=c-1;if(compareAndSetState(c,nextc))returnnextc==0;}}}
privatevoiddoAcquireSharedInterruptibly(intarg)throwsInterruptedException{finalNodenode=addWaiter(Node.SHARED);booleanfailed=true;try{for(;;){finalNodep=node.predecessor();if(p==head){intr=tryAcquireShared(arg);if(r>=0){setHeadAndPropagate(node,r);p.next=null;// help GCfailed=false;return;}}if(shouldParkAfterFailedAcquire(p,node)&&parkAndCheckInterrupt())thrownewInterruptedException();}}finally{if(failed)cancelAcquire(node);}}
首先看addWaiter方法
1234567891011121314
privateNodeaddWaiter(Nodemode){Nodenode=newNode(Thread.currentThread(),mode);// Try the fast path of enq; backup to full enq on failureNodepred=tail;if(pred!=null){node.prev=pred;if(compareAndSetTail(pred,node)){pred.next=node;returnnode;}}enq(node);returnnode;}
也就是说在pred为null的时候会初始化队列
123456789101112131415
privateNodeenq(finalNodenode){for(;;){Nodet=tail;if(t==null){// Must initializeif(compareAndSetHead(newNode()))tail=head;}else{node.prev=t;if(compareAndSetTail(t,node)){t.next=node;returnt;}}}}
privatestaticbooleanshouldParkAfterFailedAcquire(Nodepred,Nodenode){intws=pred.waitStatus;if(ws==Node.SIGNAL)/* * This node has already set status asking a release * to signal it, so it can safely park. */returntrue;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);}returnfalse;}
protectedbooleantryReleaseShared(intreleases){// Decrement count; signal when transition to zerofor(;;){intc=getState();if(c==0)returnfalse;intnextc=c-1;if(compareAndSetState(c,nextc))returnnextc==0;}}
privatevoiddoReleaseShared(){/* * 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(;;){Nodeh=head;if(h!=null&&h!=tail){intws=h.waitStatus;if(ws==Node.SIGNAL){if(!compareAndSetWaitStatus(h,Node.SIGNAL,0))continue;// loop to recheck casesunparkSuccessor(h);}elseif(ws==0&&!compareAndSetWaitStatus(h,0,Node.PROPAGATE))continue;// loop on failed CAS}if(h==head)// loop if head changedbreak;}}
privatevoidunparkSuccessor(Nodenode){/* * 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. */intws=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. */Nodes=node.next;if(s==null||s.waitStatus>0){s=null;for(Nodet=tail;t!=null&&t!=node;t=t.prev)if(t.waitStatus<=0)s=t;}if(s!=null)LockSupport.unpark(s.thread);}
privatevoidsetHeadAndPropagate(Nodenode,longpropagate){Nodeh=head;// Record old head for check belowsetHead(node);/* * Try to signal next queued node if: * Propagation was indicated by caller, * or was recorded (as h.waitStatus) 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){Nodes=node.next;if(s==null||s.isShared())doReleaseShared();}}