ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountDownLatch.java
Revision: 1.10
Committed: Tue Aug 26 00:09:18 2003 UTC (20 years, 9 months ago) by dholmes
Branch: MAIN
Changes since 1.9: +3 -3 lines
Log Message:
In response to Eamonn's comment that "best effort lower bound" is not
defined for waiting times, all such references have been deleted. The
preceding text makes it clear that the time must elapse before the
method will return, and trying to say anything about the maximum waiting
time is pointless. We can still say something to this effect in the package
docs if we want.

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 brian 1.4 * will be able to pass through await.
87     *
88     * <pre>
89     * class Driver2 { // ...
90     * void main() throws InterruptedException {
91     * CountDownLatch doneSignal = new CountDownLatch(N);
92     * Executor e = ...
93     *
94     * for (int i = 0; i < N; ++i) // create and start threads
95     * e.execute(new WorkerRunnable(doneSignal, i));
96     *
97     * doneSignal.await(); // wait for all to finish
98     * }
99     * }
100     *
101     * class WorkerRunnable implements Runnable {
102     * private final CountDownLatch doneSignal;
103     * private final int i;
104     * Worker(CountDownLatch doneSignal, int i) {
105     * this.doneSignal = doneSignal;
106     * this.i = i;
107     * }
108     * public void run() {
109     * try {
110     * doWork(i);
111     * doneSignal.countDown();
112 tim 1.7 * } catch (InterruptedException ex) {} // return;
113 brian 1.4 * }
114     *
115     * void doWork() { ... }
116     * }
117     *
118     * </pre>
119     *
120 tim 1.1 * @since 1.5
121     * @spec JSR-166
122 dholmes 1.10 * @revised $Date: 2003/08/25 22:28:11 $
123     * @editor $Author: dholmes $
124 dl 1.5 * @author Doug Lea
125 tim 1.1 */
126     public class CountDownLatch {
127 dl 1.2 private final ReentrantLock lock = new ReentrantLock();
128     private final Condition zero = lock.newCondition();
129     private int count;
130 tim 1.1
131     /**
132     * Constructs a <tt>CountDownLatch</tt> initialized with the given
133     * count.
134     *
135     * @param count the number of times {@link #countDown} must be invoked
136     * before threads can pass through {@link #await}.
137     *
138 dl 1.2 * @throws IllegalArgumentException if <tt>count</tt> is less than zero.
139 tim 1.1 */
140 dl 1.2 public CountDownLatch(int count) {
141     if (count < 0) throw new IllegalArgumentException("count < 0");
142     this.count = count;
143     }
144 tim 1.1
145     /**
146     * Causes the current thread to wait until the latch has counted down to
147     * zero, unless the thread is {@link Thread#interrupt interrupted}.
148     *
149     * <p>If the current {@link #getCount count} is zero then this method
150     * returns immediately.
151     * <p>If the current {@link #getCount count} is greater than zero then
152     * the current thread becomes disabled for thread scheduling
153     * purposes and lies dormant until one of two things happen:
154     * <ul>
155 dholmes 1.9 * <li>The count reaches zero due to invocations of the
156 tim 1.1 * {@link #countDown} method; or
157 dholmes 1.9 * <li>Some other thread {@link Thread#interrupt interrupts} the current
158 tim 1.1 * thread.
159     * </ul>
160     * <p>If the current thread:
161     * <ul>
162     * <li>has its interrupted status set on entry to this method; or
163     * <li>is {@link Thread#interrupt interrupted} while waiting,
164     * </ul>
165     * then {@link InterruptedException} is thrown and the current thread's
166     * interrupted status is cleared.
167     *
168     * @throws InterruptedException if the current thread is interrupted
169     * while waiting.
170     */
171 dl 1.2 public void await() throws InterruptedException {
172     lock.lock();
173     try {
174     while (count != 0)
175     zero.await();
176 tim 1.7 } finally {
177 dl 1.2 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 dholmes 1.10 * If the time is
213 tim 1.1 * 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 tim 1.7 } finally {
236 dl 1.2 lock.unlock();
237     }
238 tim 1.1 }
239    
240    
241 dl 1.2
242 tim 1.1 /**
243     * Decrements the count of the latch, releasing all waiting threads if
244     * the count reaches zero.
245     * <p>If the current {@link #getCount count} is greater than zero then
246     * it is decremented. If the new count is zero then all waiting threads
247     * are re-enabled for thread scheduling purposes.
248     * <p>If the current {@link #getCount count} equals zero then nothing
249     * happens.
250     */
251 dl 1.2 public void countDown() {
252     lock.lock();
253     try {
254     if (count > 0 && --count == 0)
255     zero.signalAll();
256 tim 1.7 } finally {
257 dl 1.2 lock.unlock();
258     }
259     }
260 tim 1.1
261     /**
262     * Returns the current count.
263     * <p>This method is typically used for debugging and testing purposes.
264     * @return the current count.
265     */
266     public long getCount() {
267 dl 1.2 lock.lock();
268     try {
269     return count;
270 tim 1.7 } finally {
271 dl 1.2 lock.unlock();
272     }
273 tim 1.1 }
274     }