ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountDownLatch.java
Revision: 1.13
Committed: Mon Nov 3 00:11:46 2003 UTC (20 years, 7 months ago) by dl
Branch: MAIN
CVS Tags: JSR166_NOV3_FREEZE, JSR166_DEC9_PRE_ES_SUBMIT, JSR166_DEC9_POST_ES_SUBMIT
Changes since 1.12: +3 -2 lines
Log Message:
Fixed typo in example

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 dl 1.6 import java.util.concurrent.locks.*;
9 tim 1.1
10     /**
11 brian 1.4 * A synchronization aid that allows one or more threads to wait until
12     * a set of operations being performed in other threads completes.
13 dl 1.3 *
14     * <p>A <tt>CountDownLatch</tt> is initialized with a given
15 dholmes 1.9 * <em>count</em>. The {@link #await await} methods block until the current
16 dl 1.3 * {@link #getCount count} reaches zero due to invocations of the
17     * {@link #countDown} method, after which all waiting threads are
18 dholmes 1.9 * released and any subsequent invocations of {@link #await await} return
19 dl 1.3 * 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 tim 1.1 *
23     * <p>A <tt>CountDownLatch</tt> is a versatile synchronization tool
24 dl 1.5 * and can be used for a number of purposes. A
25     * <tt>CountDownLatch</tt> initialized with a count of one serves as a
26 dholmes 1.9 * simple on/off latch, or gate: all threads invoking {@link #await await}
27 dl 1.5 * 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 dholmes 1.9 * thread from proceeding past an {@link #await await} until all
35 dl 1.5 * threads could pass.
36 tim 1.1 *
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 dholmes 1.9 * <li>The first is a start signal that prevents any worker from proceeding
41 tim 1.1 * until the driver is ready for them to proceed;
42 dholmes 1.9 * <li>The second is a completion signal that allows the driver to wait
43 tim 1.1 * 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 tim 1.7 * } catch (InterruptedException ex) {} // return;
75 tim 1.1 * }
76     *
77     * void doWork() { ... }
78     * }
79     *
80     * </pre>
81     *
82 dl 1.5 * <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 dl 1.13 * will be able to pass through await. (When threads must repeatedly
87     * count down in this way, instead use a {@link CyclicBarrier}.)
88 brian 1.4 *
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 dl 1.13 * WorkerRunnable(CountDownLatch doneSignal, int i) {
106 brian 1.4 * this.doneSignal = doneSignal;
107     * this.i = i;
108     * }
109     * public void run() {
110     * try {
111     * doWork(i);
112     * doneSignal.countDown();
113 tim 1.7 * } catch (InterruptedException ex) {} // return;
114 brian 1.4 * }
115     *
116     * void doWork() { ... }
117     * }
118     *
119     * </pre>
120     *
121 tim 1.1 * @since 1.5
122 dl 1.5 * @author Doug Lea
123 tim 1.1 */
124     public class CountDownLatch {
125 dl 1.2 private final ReentrantLock lock = new ReentrantLock();
126 dl 1.12 private final ReentrantLock.ConditionObject zero = lock.newCondition();
127 dl 1.2 private int count;
128 tim 1.1
129     /**
130     * Constructs a <tt>CountDownLatch</tt> initialized with the given
131     * count.
132     *
133     * @param count the number of times {@link #countDown} must be invoked
134     * before threads can pass through {@link #await}.
135     *
136 dl 1.2 * @throws IllegalArgumentException if <tt>count</tt> is less than zero.
137 tim 1.1 */
138 dl 1.2 public CountDownLatch(int count) {
139     if (count < 0) throw new IllegalArgumentException("count < 0");
140     this.count = count;
141     }
142 tim 1.1
143     /**
144     * Causes the current thread to wait until the latch has counted down to
145     * zero, unless the thread is {@link Thread#interrupt interrupted}.
146     *
147     * <p>If the current {@link #getCount count} is zero then this method
148     * returns immediately.
149     * <p>If the current {@link #getCount count} is greater than zero then
150     * the current thread becomes disabled for thread scheduling
151     * purposes and lies dormant until one of two things happen:
152     * <ul>
153 dholmes 1.9 * <li>The count reaches zero due to invocations of the
154 tim 1.1 * {@link #countDown} method; or
155 dholmes 1.9 * <li>Some other thread {@link Thread#interrupt interrupts} the current
156 tim 1.1 * thread.
157     * </ul>
158     * <p>If the current thread:
159     * <ul>
160     * <li>has its interrupted status set on entry to this method; or
161     * <li>is {@link Thread#interrupt interrupted} while waiting,
162     * </ul>
163     * then {@link InterruptedException} is thrown and the current thread's
164     * interrupted status is cleared.
165     *
166     * @throws InterruptedException if the current thread is interrupted
167     * while waiting.
168     */
169 dl 1.2 public void await() throws InterruptedException {
170     lock.lock();
171     try {
172     while (count != 0)
173     zero.await();
174 tim 1.7 } finally {
175 dl 1.2 lock.unlock();
176     }
177     }
178    
179 tim 1.1
180     /**
181     * Causes the current thread to wait until the latch has counted down to
182     * zero, unless the thread is {@link Thread#interrupt interrupted},
183     * or the specified waiting time elapses.
184     *
185     * <p>If the current {@link #getCount count} is zero then this method
186     * returns immediately with the value <tt>true</tt>.
187     *
188     * <p>If the current {@link #getCount count} is greater than zero then
189     * the current thread becomes disabled for thread scheduling
190     * purposes and lies dormant until one of three things happen:
191     * <ul>
192     * <li>The count reaches zero due to invocations of the
193     * {@link #countDown} method; or
194     * <li>Some other thread {@link Thread#interrupt interrupts} the current
195     * thread; or
196     * <li>The specified waiting time elapses.
197     * </ul>
198     * <p>If the count reaches zero then the method returns with the
199     * value <tt>true</tt>.
200     * <p>If the current thread:
201     * <ul>
202     * <li>has its interrupted status set on entry to this method; or
203     * <li>is {@link Thread#interrupt interrupted} while waiting,
204     * </ul>
205     * then {@link InterruptedException} is thrown and the current thread's
206     * interrupted status is cleared.
207     *
208     * <p>If the specified waiting time elapses then the value <tt>false</tt>
209     * is returned.
210 dholmes 1.10 * If the time is
211 tim 1.1 * less than or equal to zero, the method will not wait at all.
212     *
213     * @param timeout the maximum time to wait
214 dl 1.2 * @param unit the time unit of the <tt>timeout</tt> argument.
215 tim 1.1 * @return <tt>true</tt> if the count reached zero and <tt>false</tt>
216     * if the waiting time elapsed before the count reached zero.
217     *
218     * @throws InterruptedException if the current thread is interrupted
219     * while waiting.
220     */
221 dl 1.2 public boolean await(long timeout, TimeUnit unit)
222 tim 1.1 throws InterruptedException {
223 dl 1.2 long nanos = unit.toNanos(timeout);
224     lock.lock();
225     try {
226     for (;;) {
227     if (count == 0)
228     return true;
229     nanos = zero.awaitNanos(nanos);
230     if (nanos <= 0)
231     return false;
232     }
233 tim 1.7 } finally {
234 dl 1.2 lock.unlock();
235     }
236 tim 1.1 }
237    
238    
239 dl 1.2
240 tim 1.1 /**
241     * Decrements the count of the latch, releasing all waiting threads if
242     * the count reaches zero.
243     * <p>If the current {@link #getCount count} is greater than zero then
244     * it is decremented. If the new count is zero then all waiting threads
245     * are re-enabled for thread scheduling purposes.
246     * <p>If the current {@link #getCount count} equals zero then nothing
247     * happens.
248     */
249 dl 1.2 public void countDown() {
250     lock.lock();
251     try {
252     if (count > 0 && --count == 0)
253     zero.signalAll();
254 tim 1.7 } finally {
255 dl 1.2 lock.unlock();
256     }
257     }
258 tim 1.1
259     /**
260     * Returns the current count.
261     * <p>This method is typically used for debugging and testing purposes.
262     * @return the current count.
263     */
264     public long getCount() {
265 dl 1.2 lock.lock();
266     try {
267     return count;
268 tim 1.7 } finally {
269 dl 1.2 lock.unlock();
270     }
271 tim 1.1 }
272     }