Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: edu/emory/mathcs/util/concurrent/CountDownLatch.java


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