ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountDownLatch.java
Revision: 1.4
Committed: Mon Jun 23 02:26:16 2003 UTC (20 years, 11 months ago) by brian
Branch: MAIN
Changes since 1.3: +47 -8 lines
Log Message:
Partial javadoc pass

File Contents

# User Rev Content
1 dl 1.2 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain. Use, modify, and
4     * redistribute this code in any way without acknowledgement.
5     */
6    
7 tim 1.1 package java.util.concurrent;
8    
9     /**
10 brian 1.4 * A synchronization aid that allows one or more threads to wait until
11     * a set of operations being performed in other threads completes.
12 dl 1.3 *
13     * <p>A <tt>CountDownLatch</tt> is initialized with a given
14     * <em>count</em>. The {@link #await} methods block until the current
15     * {@link #getCount count} reaches zero due to invocations of the
16     * {@link #countDown} method, after which all waiting threads are
17 tim 1.1 * released and any subsequent invocations of {@link #await} return
18 dl 1.3 * immediately. This is a one-shot phenomenon -- the count cannot be
19     * reset. If you need a version that resets the count, consider using
20     * a {@link CyclicBarrier}.
21 tim 1.1 *
22     * <p>A <tt>CountDownLatch</tt> is a versatile synchronization tool
23     * and can be used for a number of purposes.
24 brian 1.4 * A <tt>CountDownLatch</tt> initialized with a count of one serves as a simple on/off
25 tim 1.1 * latch, or gate: all threads invoking {@link #await} wait at the gate until
26     * it is opened by a thread invoking {@link #countDown}.
27     * A <tt>CountDownLatch</tt> initialized to <em>N</em> can be used to make
28 brian 1.4 * one thread wait until <em>N</em> threads have completed some action, or some
29     * action has been completed N times.
30     * <p>A useful property of a <tt>CountDownLatch</tt> is that it doesn't
31     * require that threads calling <tt>countDown</tt> wait for the count to reach zero
32     * before proceeding, it simply
33 tim 1.1 * prevents any thread from proceeding past the {@link #await wait} until
34     * all threads could pass.
35     *
36     * <p><b>Sample usage:</b> Here is a pair of classes in which a group
37     * of worker threads use two countdown latches:
38     * <ul>
39     * <li> The first is a start signal that prevents any worker from proceeding
40     * until the driver is ready for them to proceed;
41     * <li> The second is a completion signal that allows the driver to wait
42     * until all workers have completed.
43     * </ul>
44     *
45     * <pre>
46     * class Driver { // ...
47     * void main() throws InterruptedException {
48     * CountDownLatch startSignal = new CountDownLatch(1);
49     * CountDownLatch doneSignal = new CountDownLatch(N);
50     *
51     * for (int i = 0; i < N; ++i) // create and start threads
52     * new Thread(new Worker(startSignal, doneSignal)).start();
53     *
54     * doSomethingElse(); // don't let run yet
55     * startSignal.countDown(); // let all threads proceed
56     * doSomethingElse();
57     * doneSignal.await(); // wait for all to finish
58     * }
59     * }
60     *
61     * class Worker implements Runnable {
62     * private final CountDownLatch startSignal;
63     * private final CountDownLatch doneSignal;
64     * Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
65     * this.startSignal = startSignal;
66     * this.doneSignal = doneSignal;
67     * }
68     * public void run() {
69     * try {
70     * startSignal.await();
71     * doWork();
72     * doneSignal.countDown();
73     * }
74     * catch (InterruptedException ex) {} // return;
75     * }
76     *
77     * void doWork() { ... }
78     * }
79     *
80     * </pre>
81     *
82 brian 1.4 * <p>Another typical usage would be to divide a problem into N parts, describe each part
83     * with a Runnable that executes that portion and counts down on the latch, and queue all
84     * the Runnables to an Executor. When all sub-parts are complete, the coordinating thread
85     * will be able to pass through await.
86     *
87     * <pre>
88     * class Driver2 { // ...
89     * void main() throws InterruptedException {
90     * CountDownLatch doneSignal = new CountDownLatch(N);
91     * Executor e = ...
92     *
93     * for (int i = 0; i < N; ++i) // create and start threads
94     * e.execute(new WorkerRunnable(doneSignal, i));
95     *
96     * doneSignal.await(); // wait for all to finish
97     * }
98     * }
99     *
100     * class WorkerRunnable implements Runnable {
101     * private final CountDownLatch doneSignal;
102     * private final int i;
103     * Worker(CountDownLatch doneSignal, int i) {
104     * this.doneSignal = doneSignal;
105     * this.i = i;
106     * }
107     * public void run() {
108     * try {
109     * doWork(i);
110     * doneSignal.countDown();
111     * }
112     * catch (InterruptedException ex) {} // return;
113     * }
114     *
115     * void doWork() { ... }
116     * }
117     *
118     * </pre>
119     *
120 tim 1.1 * @since 1.5
121     * @spec JSR-166
122 brian 1.4 * @revised $Date: 2003/06/07 18:20:20 $
123 dl 1.3 * @editor $Author: dl $
124 tim 1.1 */
125     public class CountDownLatch {
126 dl 1.2 private final ReentrantLock lock = new ReentrantLock();
127     private final Condition zero = lock.newCondition();
128     private int count;
129 tim 1.1
130     /**
131     * Constructs a <tt>CountDownLatch</tt> initialized with the given
132     * count.
133     *
134     * @param count the number of times {@link #countDown} must be invoked
135     * before threads can pass through {@link #await}.
136     *
137 dl 1.2 * @throws IllegalArgumentException if <tt>count</tt> is less than zero.
138 tim 1.1 */
139 dl 1.2 public CountDownLatch(int count) {
140     if (count < 0) throw new IllegalArgumentException("count < 0");
141     this.count = count;
142     }
143 tim 1.1
144     /**
145     * Causes the current thread to wait until the latch has counted down to
146     * zero, unless the thread is {@link Thread#interrupt interrupted}.
147     *
148     * <p>If the current {@link #getCount count} is zero then this method
149     * returns immediately.
150     * <p>If the current {@link #getCount count} is greater than zero then
151     * the current thread becomes disabled for thread scheduling
152     * purposes and lies dormant until one of two things happen:
153     * <ul>
154     * <li> The count reaches zero due to invocations of the
155     * {@link #countDown} method; or
156     * <li> Some other thread {@link Thread#interrupt interrupts} the current
157     * thread.
158     * </ul>
159     * <p>If the current thread:
160     * <ul>
161     * <li>has its interrupted status set on entry to this method; or
162     * <li>is {@link Thread#interrupt interrupted} while waiting,
163     * </ul>
164     * then {@link InterruptedException} is thrown and the current thread's
165     * interrupted status is cleared.
166     *
167     * @throws InterruptedException if the current thread is interrupted
168     * while waiting.
169     */
170 dl 1.2 public void await() throws InterruptedException {
171     lock.lock();
172     try {
173     while (count != 0)
174     zero.await();
175     }
176     finally {
177     lock.unlock();
178     }
179     }
180    
181 tim 1.1
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     * The given waiting time is a best-effort lower bound. 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 dl 1.2 * @param unit the time unit of the <tt>timeout</tt> argument.
217 tim 1.1 * @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 dl 1.2 public boolean await(long timeout, TimeUnit unit)
224 tim 1.1 throws InterruptedException {
225 dl 1.2 long nanos = unit.toNanos(timeout);
226     lock.lock();
227     try {
228     for (;;) {
229     if (count == 0)
230     return true;
231     nanos = zero.awaitNanos(nanos);
232     if (nanos <= 0)
233     return false;
234     }
235     }
236     finally {
237     lock.unlock();
238     }
239 tim 1.1 }
240    
241    
242 dl 1.2
243 tim 1.1 /**
244     * Decrements the count of the latch, releasing all waiting threads if
245     * the count reaches zero.
246     * <p>If the current {@link #getCount count} is greater than zero then
247     * it is decremented. If the new count is zero then all waiting threads
248     * are re-enabled for thread scheduling purposes.
249     * <p>If the current {@link #getCount count} equals zero then nothing
250     * happens.
251     */
252 dl 1.2 public void countDown() {
253     lock.lock();
254     try {
255     if (count > 0 && --count == 0)
256     zero.signalAll();
257     }
258     finally {
259     lock.unlock();
260     }
261     }
262 tim 1.1
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 long getCount() {
269 dl 1.2 lock.lock();
270     try {
271     return count;
272     }
273     finally {
274     lock.unlock();
275     }
276 tim 1.1 }
277     }