1. /*
  2. * @(#)CountDownLatch.java 1.5 04/02/09
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util.concurrent;
  8. import java.util.concurrent.locks.*;
  9. import java.util.concurrent.atomic.*;
  10. /**
  11. * A synchronization aid that allows one or more threads to wait until
  12. * a set of operations being performed in other threads completes.
  13. *
  14. * <p>A <tt>CountDownLatch</tt> is initialized with a given
  15. * <em>count</em>. The {@link #await await} methods block until the current
  16. * {@link #getCount count} reaches zero due to invocations of the
  17. * {@link #countDown} method, after which all waiting threads are
  18. * released and any subsequent invocations of {@link #await await} return
  19. * immediately. This is a one-shot phenomenon -- the count cannot be
  20. * reset. If you need a version that resets the count, consider using
  21. * a {@link CyclicBarrier}.
  22. *
  23. * <p>A <tt>CountDownLatch</tt> is a versatile synchronization tool
  24. * and can be used for a number of purposes. A
  25. * <tt>CountDownLatch</tt> initialized with a count of one serves as a
  26. * simple on/off latch, or gate: all threads invoking {@link #await await}
  27. * wait at the gate until it is opened by a thread invoking {@link
  28. * #countDown}. A <tt>CountDownLatch</tt> initialized to <em>N</em>
  29. * can be used to make one thread wait until <em>N</em> threads have
  30. * completed some action, or some action has been completed N times.
  31. * <p>A useful property of a <tt>CountDownLatch</tt> is that it
  32. * doesn't require that threads calling <tt>countDown</tt> wait for
  33. * the count to reach zero before proceeding, it simply prevents any
  34. * thread from proceeding past an {@link #await await} until all
  35. * threads could pass.
  36. *
  37. * <p><b>Sample usage:</b> Here is a pair of classes in which a group
  38. * of worker threads use two countdown latches:
  39. * <ul>
  40. * <li>The first is a start signal that prevents any worker from proceeding
  41. * until the driver is ready for them to proceed;
  42. * <li>The second is a completion signal that allows the driver to wait
  43. * until all workers have completed.
  44. * </ul>
  45. *
  46. * <pre>
  47. * class Driver { // ...
  48. * void main() throws InterruptedException {
  49. * CountDownLatch startSignal = new CountDownLatch(1);
  50. * CountDownLatch doneSignal = new CountDownLatch(N);
  51. *
  52. * for (int i = 0; i < N; ++i) // create and start threads
  53. * new Thread(new Worker(startSignal, doneSignal)).start();
  54. *
  55. * doSomethingElse(); // don't let run yet
  56. * startSignal.countDown(); // let all threads proceed
  57. * doSomethingElse();
  58. * doneSignal.await(); // wait for all to finish
  59. * }
  60. * }
  61. *
  62. * class Worker implements Runnable {
  63. * private final CountDownLatch startSignal;
  64. * private final CountDownLatch doneSignal;
  65. * Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
  66. * this.startSignal = startSignal;
  67. * this.doneSignal = doneSignal;
  68. * }
  69. * public void run() {
  70. * try {
  71. * startSignal.await();
  72. * doWork();
  73. * doneSignal.countDown();
  74. * } catch (InterruptedException ex) {} // return;
  75. * }
  76. *
  77. * void doWork() { ... }
  78. * }
  79. *
  80. * </pre>
  81. *
  82. * <p>Another typical usage would be to divide a problem into N parts,
  83. * describe each part with a Runnable that executes that portion and
  84. * counts down on the latch, and queue all the Runnables to an
  85. * Executor. When all sub-parts are complete, the coordinating thread
  86. * will be able to pass through await. (When threads must repeatedly
  87. * count down in this way, instead use a {@link CyclicBarrier}.)
  88. *
  89. * <pre>
  90. * class Driver2 { // ...
  91. * void main() throws InterruptedException {
  92. * CountDownLatch doneSignal = new CountDownLatch(N);
  93. * Executor e = ...
  94. *
  95. * for (int i = 0; i < N; ++i) // create and start threads
  96. * e.execute(new WorkerRunnable(doneSignal, i));
  97. *
  98. * doneSignal.await(); // wait for all to finish
  99. * }
  100. * }
  101. *
  102. * class WorkerRunnable implements Runnable {
  103. * private final CountDownLatch doneSignal;
  104. * private final int i;
  105. * WorkerRunnable(CountDownLatch doneSignal, int i) {
  106. * this.doneSignal = doneSignal;
  107. * this.i = i;
  108. * }
  109. * public void run() {
  110. * try {
  111. * doWork(i);
  112. * doneSignal.countDown();
  113. * } catch (InterruptedException ex) {} // return;
  114. * }
  115. *
  116. * void doWork() { ... }
  117. * }
  118. *
  119. * </pre>
  120. *
  121. * @since 1.5
  122. * @author Doug Lea
  123. */
  124. public class CountDownLatch {
  125. /**
  126. * Synchronization control For CountDownLatch.
  127. * Uses AQS state to represent count.
  128. */
  129. private static final class Sync extends AbstractQueuedSynchronizer {
  130. Sync(int count) {
  131. setState(count);
  132. }
  133. int getCount() {
  134. return getState();
  135. }
  136. public int tryAcquireShared(int acquires) {
  137. return getState() == 0? 1 : -1;
  138. }
  139. public boolean tryReleaseShared(int releases) {
  140. // Decrement count; signal when transition to zero
  141. for (;;) {
  142. int c = getState();
  143. if (c == 0)
  144. return false;
  145. int nextc = c-1;
  146. if (compareAndSetState(c, nextc))
  147. return nextc == 0;
  148. }
  149. }
  150. }
  151. private final Sync sync;
  152. /**
  153. * Constructs a <tt>CountDownLatch</tt> initialized with the given
  154. * count.
  155. *
  156. * @param count the number of times {@link #countDown} must be invoked
  157. * before threads can pass through {@link #await}.
  158. *
  159. * @throws IllegalArgumentException if <tt>count</tt> is less than zero.
  160. */
  161. public CountDownLatch(int count) {
  162. if (count < 0) throw new IllegalArgumentException("count < 0");
  163. this.sync = new Sync(count);
  164. }
  165. /**
  166. * Causes the current thread to wait until the latch has counted down to
  167. * zero, unless the thread is {@link Thread#interrupt interrupted}.
  168. *
  169. * <p>If the current {@link #getCount count} is zero then this method
  170. * returns immediately.
  171. * <p>If the current {@link #getCount count} is greater than zero then
  172. * the current thread becomes disabled for thread scheduling
  173. * purposes and lies dormant until one of two things happen:
  174. * <ul>
  175. * <li>The count reaches zero due to invocations of the
  176. * {@link #countDown} method; or
  177. * <li>Some other thread {@link Thread#interrupt interrupts} the current
  178. * thread.
  179. * </ul>
  180. * <p>If the current thread:
  181. * <ul>
  182. * <li>has its interrupted status set on entry to this method; or
  183. * <li>is {@link Thread#interrupt interrupted} while waiting,
  184. * </ul>
  185. * then {@link InterruptedException} is thrown and the current thread's
  186. * interrupted status is cleared.
  187. *
  188. * @throws InterruptedException if the current thread is interrupted
  189. * while waiting.
  190. */
  191. public void await() throws InterruptedException {
  192. sync.acquireSharedInterruptibly(1);
  193. }
  194. /**
  195. * Causes the current thread to wait until the latch has counted down to
  196. * zero, unless the thread is {@link Thread#interrupt interrupted},
  197. * or the specified waiting time elapses.
  198. *
  199. * <p>If the current {@link #getCount count} is zero then this method
  200. * returns immediately with the value <tt>true</tt>.
  201. *
  202. * <p>If the current {@link #getCount count} is greater than zero then
  203. * the current thread becomes disabled for thread scheduling
  204. * purposes and lies dormant until one of three things happen:
  205. * <ul>
  206. * <li>The count reaches zero due to invocations of the
  207. * {@link #countDown} method; or
  208. * <li>Some other thread {@link Thread#interrupt interrupts} the current
  209. * thread; or
  210. * <li>The specified waiting time elapses.
  211. * </ul>
  212. * <p>If the count reaches zero then the method returns with the
  213. * value <tt>true</tt>.
  214. * <p>If the current thread:
  215. * <ul>
  216. * <li>has its interrupted status set on entry to this method; or
  217. * <li>is {@link Thread#interrupt interrupted} while waiting,
  218. * </ul>
  219. * then {@link InterruptedException} is thrown and the current thread's
  220. * interrupted status is cleared.
  221. *
  222. * <p>If the specified waiting time elapses then the value <tt>false</tt>
  223. * is returned.
  224. * If the time is
  225. * less than or equal to zero, the method will not wait at all.
  226. *
  227. * @param timeout the maximum time to wait
  228. * @param unit the time unit of the <tt>timeout</tt> argument.
  229. * @return <tt>true</tt> if the count reached zero and <tt>false</tt>
  230. * if the waiting time elapsed before the count reached zero.
  231. *
  232. * @throws InterruptedException if the current thread is interrupted
  233. * while waiting.
  234. */
  235. public boolean await(long timeout, TimeUnit unit)
  236. throws InterruptedException {
  237. return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
  238. }
  239. /**
  240. * Decrements the count of the latch, releasing all waiting threads if
  241. * the count reaches zero.
  242. * <p>If the current {@link #getCount count} is greater than zero then
  243. * it is decremented. If the new count is zero then all waiting threads
  244. * are re-enabled for thread scheduling purposes.
  245. * <p>If the current {@link #getCount count} equals zero then nothing
  246. * happens.
  247. */
  248. public void countDown() {
  249. sync.releaseShared(1);
  250. }
  251. /**
  252. * Returns the current count.
  253. * <p>This method is typically used for debugging and testing purposes.
  254. * @return the current count.
  255. */
  256. public long getCount() {
  257. return sync.getCount();
  258. }
  259. /**
  260. * Returns a string identifying this latch, as well as its state.
  261. * The state, in brackets, includes the String
  262. * "Count =" followed by the current count.
  263. * @return a string identifying this latch, as well as its
  264. * state
  265. */
  266. public String toString() {
  267. return super.toString() + "[Count = " + sync.getCount() + "]";
  268. }
  269. }