ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountDownLatch.java
Revision: 1.6
Committed: Tue Jul 8 00:46:33 2003 UTC (20 years, 11 months ago) by dl
Branch: MAIN
CVS Tags: JSR166_CR1, JSR166_PRELIMINARY_TEST_RELEASE_2
Changes since 1.5: +3 -2 lines
Log Message:
Locks in subpackage; fairness params added

File Contents

# Content
1 /*
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 package java.util.concurrent;
8 import java.util.concurrent.locks.*;
9
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} 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} 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}
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 the {@link #await wait} 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 * }
75 * catch (InterruptedException ex) {} // return;
76 * }
77 *
78 * void doWork() { ... }
79 * }
80 *
81 * </pre>
82 *
83 * <p>Another typical usage would be to divide a problem into N parts,
84 * describe each part with a Runnable that executes that portion and
85 * counts down on the latch, and queue all the Runnables to an
86 * Executor. When all sub-parts are complete, the coordinating thread
87 * will be able to pass through await.
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 * Worker(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 * }
114 * catch (InterruptedException ex) {} // return;
115 * }
116 *
117 * void doWork() { ... }
118 * }
119 *
120 * </pre>
121 *
122 * @since 1.5
123 * @spec JSR-166
124 * @revised $Date: 2003/06/24 14:34:47 $
125 * @editor $Author: dl $
126 * @author Doug Lea
127 */
128 public class CountDownLatch {
129 private final ReentrantLock lock = new ReentrantLock();
130 private final Condition zero = lock.newCondition();
131 private int count;
132
133 /**
134 * Constructs a <tt>CountDownLatch</tt> initialized with the given
135 * count.
136 *
137 * @param count the number of times {@link #countDown} must be invoked
138 * before threads can pass through {@link #await}.
139 *
140 * @throws IllegalArgumentException if <tt>count</tt> is less than zero.
141 */
142 public CountDownLatch(int count) {
143 if (count < 0) throw new IllegalArgumentException("count < 0");
144 this.count = 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 lock.lock();
175 try {
176 while (count != 0)
177 zero.await();
178 }
179 finally {
180 lock.unlock();
181 }
182 }
183
184
185 /**
186 * Causes the current thread to wait until the latch has counted down to
187 * zero, unless the thread is {@link Thread#interrupt interrupted},
188 * or the specified waiting time elapses.
189 *
190 * <p>If the current {@link #getCount count} is zero then this method
191 * returns immediately with the value <tt>true</tt>.
192 *
193 * <p>If the current {@link #getCount count} is greater than zero then
194 * the current thread becomes disabled for thread scheduling
195 * purposes and lies dormant until one of three things happen:
196 * <ul>
197 * <li>The count reaches zero due to invocations of the
198 * {@link #countDown} method; or
199 * <li>Some other thread {@link Thread#interrupt interrupts} the current
200 * thread; or
201 * <li>The specified waiting time elapses.
202 * </ul>
203 * <p>If the count reaches zero then the method returns with the
204 * value <tt>true</tt>.
205 * <p>If the current thread:
206 * <ul>
207 * <li>has its interrupted status set on entry to this method; or
208 * <li>is {@link Thread#interrupt interrupted} while waiting,
209 * </ul>
210 * then {@link InterruptedException} is thrown and the current thread's
211 * interrupted status is cleared.
212 *
213 * <p>If the specified waiting time elapses then the value <tt>false</tt>
214 * is returned.
215 * The given waiting time is a best-effort lower bound. If the time is
216 * less than or equal to zero, the method will not wait at all.
217 *
218 * @param timeout the maximum time to wait
219 * @param unit the time unit of the <tt>timeout</tt> argument.
220 * @return <tt>true</tt> if the count reached zero and <tt>false</tt>
221 * if the waiting time elapsed before the count reached zero.
222 *
223 * @throws InterruptedException if the current thread is interrupted
224 * while waiting.
225 */
226 public boolean await(long timeout, TimeUnit unit)
227 throws InterruptedException {
228 long nanos = unit.toNanos(timeout);
229 lock.lock();
230 try {
231 for (;;) {
232 if (count == 0)
233 return true;
234 nanos = zero.awaitNanos(nanos);
235 if (nanos <= 0)
236 return false;
237 }
238 }
239 finally {
240 lock.unlock();
241 }
242 }
243
244
245
246 /**
247 * Decrements the count of the latch, releasing all waiting threads if
248 * the count reaches zero.
249 * <p>If the current {@link #getCount count} is greater than zero then
250 * it is decremented. If the new count is zero then all waiting threads
251 * are re-enabled for thread scheduling purposes.
252 * <p>If the current {@link #getCount count} equals zero then nothing
253 * happens.
254 */
255 public void countDown() {
256 lock.lock();
257 try {
258 if (count > 0 && --count == 0)
259 zero.signalAll();
260 }
261 finally {
262 lock.unlock();
263 }
264 }
265
266 /**
267 * Returns the current count.
268 * <p>This method is typically used for debugging and testing purposes.
269 * @return the current count.
270 */
271 public long getCount() {
272 lock.lock();
273 try {
274 return count;
275 }
276 finally {
277 lock.unlock();
278 }
279 }
280 }