ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountDownLatch.java
Revision: 1.17
Committed: Wed Dec 31 21:30:00 2003 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.16: +15 -8 lines
Log Message:
AQS API improvements

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, as explained at
4 * http://creativecommons.org/licenses/publicdomain
5 */
6
7 package java.util.concurrent;
8 import java.util.concurrent.locks.*;
9 import java.util.concurrent.atomic.*;
10
11 /**
12 * A synchronization aid that allows one or more threads to wait until
13 * a set of operations being performed in other threads completes.
14 *
15 * <p>A <tt>CountDownLatch</tt> is initialized with a given
16 * <em>count</em>. The {@link #await await} methods block until the current
17 * {@link #getCount count} reaches zero due to invocations of the
18 * {@link #countDown} method, after which all waiting threads are
19 * released and any subsequent invocations of {@link #await await} return
20 * immediately. This is a one-shot phenomenon -- the count cannot be
21 * reset. If you need a version that resets the count, consider using
22 * a {@link CyclicBarrier}.
23 *
24 * <p>A <tt>CountDownLatch</tt> is a versatile synchronization tool
25 * and can be used for a number of purposes. A
26 * <tt>CountDownLatch</tt> initialized with a count of one serves as a
27 * simple on/off latch, or gate: all threads invoking {@link #await await}
28 * wait at the gate until it is opened by a thread invoking {@link
29 * #countDown}. A <tt>CountDownLatch</tt> initialized to <em>N</em>
30 * can be used to make one thread wait until <em>N</em> threads have
31 * completed some action, or some action has been completed N times.
32 * <p>A useful property of a <tt>CountDownLatch</tt> is that it
33 * doesn't require that threads calling <tt>countDown</tt> wait for
34 * the count to reach zero before proceeding, it simply prevents any
35 * thread from proceeding past an {@link #await await} until all
36 * threads could pass.
37 *
38 * <p><b>Sample usage:</b> Here is a pair of classes in which a group
39 * of worker threads use two countdown latches:
40 * <ul>
41 * <li>The first is a start signal that prevents any worker from proceeding
42 * until the driver is ready for them to proceed;
43 * <li>The second is a completion signal that allows the driver to wait
44 * until all workers have completed.
45 * </ul>
46 *
47 * <pre>
48 * class Driver { // ...
49 * void main() throws InterruptedException {
50 * CountDownLatch startSignal = new CountDownLatch(1);
51 * CountDownLatch doneSignal = new CountDownLatch(N);
52 *
53 * for (int i = 0; i < N; ++i) // create and start threads
54 * new Thread(new Worker(startSignal, doneSignal)).start();
55 *
56 * doSomethingElse(); // don't let run yet
57 * startSignal.countDown(); // let all threads proceed
58 * doSomethingElse();
59 * doneSignal.await(); // wait for all to finish
60 * }
61 * }
62 *
63 * class Worker implements Runnable {
64 * private final CountDownLatch startSignal;
65 * private final CountDownLatch doneSignal;
66 * Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
67 * this.startSignal = startSignal;
68 * this.doneSignal = doneSignal;
69 * }
70 * public void run() {
71 * try {
72 * startSignal.await();
73 * doWork();
74 * doneSignal.countDown();
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. (When threads must repeatedly
88 * count down in this way, instead use a {@link CyclicBarrier}.)
89 *
90 * <pre>
91 * class Driver2 { // ...
92 * void main() throws InterruptedException {
93 * CountDownLatch doneSignal = new CountDownLatch(N);
94 * Executor e = ...
95 *
96 * for (int i = 0; i < N; ++i) // create and start threads
97 * e.execute(new WorkerRunnable(doneSignal, i));
98 *
99 * doneSignal.await(); // wait for all to finish
100 * }
101 * }
102 *
103 * class WorkerRunnable implements Runnable {
104 * private final CountDownLatch doneSignal;
105 * private final int i;
106 * WorkerRunnable(CountDownLatch doneSignal, int i) {
107 * this.doneSignal = doneSignal;
108 * this.i = i;
109 * }
110 * public void run() {
111 * try {
112 * doWork(i);
113 * doneSignal.countDown();
114 * } catch (InterruptedException ex) {} // return;
115 * }
116 *
117 * void doWork() { ... }
118 * }
119 *
120 * </pre>
121 *
122 * @since 1.5
123 * @author Doug Lea
124 */
125 public class CountDownLatch {
126 /**
127 * Synchronization control For CountDownLatch.
128 * Uses AQS state to represent count.
129 */
130 private static final class Sync extends AbstractQueuedSynchronizer {
131 Sync(int count) {
132 setState(count);
133 }
134
135 int getCount() {
136 return getState();
137 }
138
139 public int tryAcquireSharedState(boolean isQueued, int acquires) {
140 return getState() == 0? 1 : -1;
141 }
142
143 public boolean releaseSharedState(int releases) {
144 // Decrement count; signal when transition to zero
145 for (;;) {
146 int c = getState();
147 if (c == 0)
148 return false;
149 if (compareAndSetState(c, c-1))
150 return c == 1;
151 }
152 }
153 }
154
155 private final Sync sync;
156 /**
157 * Constructs a <tt>CountDownLatch</tt> initialized with the given
158 * count.
159 *
160 * @param count the number of times {@link #countDown} must be invoked
161 * before threads can pass through {@link #await}.
162 *
163 * @throws IllegalArgumentException if <tt>count</tt> is less than zero.
164 */
165 public CountDownLatch(int count) {
166 if (count < 0) throw new IllegalArgumentException("count < 0");
167 this.sync = new Sync(count);
168 }
169
170 /**
171 * Causes the current thread to wait until the latch has counted down to
172 * zero, unless the thread is {@link Thread#interrupt interrupted}.
173 *
174 * <p>If the current {@link #getCount count} is zero then this method
175 * returns immediately.
176 * <p>If the current {@link #getCount count} is greater than zero then
177 * the current thread becomes disabled for thread scheduling
178 * purposes and lies dormant until one of two things happen:
179 * <ul>
180 * <li>The count reaches zero due to invocations of the
181 * {@link #countDown} method; or
182 * <li>Some other thread {@link Thread#interrupt interrupts} the current
183 * thread.
184 * </ul>
185 * <p>If the current thread:
186 * <ul>
187 * <li>has its interrupted status set on entry to this method; or
188 * <li>is {@link Thread#interrupt interrupted} while waiting,
189 * </ul>
190 * then {@link InterruptedException} is thrown and the current thread's
191 * interrupted status is cleared.
192 *
193 * @throws InterruptedException if the current thread is interrupted
194 * while waiting.
195 */
196 public void await() throws InterruptedException {
197 sync.acquireSharedInterruptibly(1);
198 }
199
200 /**
201 * Causes the current thread to wait until the latch has counted down to
202 * zero, unless the thread is {@link Thread#interrupt interrupted},
203 * or the specified waiting time elapses.
204 *
205 * <p>If the current {@link #getCount count} is zero then this method
206 * returns immediately with the value <tt>true</tt>.
207 *
208 * <p>If the current {@link #getCount count} is greater than zero then
209 * the current thread becomes disabled for thread scheduling
210 * purposes and lies dormant until one of three things happen:
211 * <ul>
212 * <li>The count reaches zero due to invocations of the
213 * {@link #countDown} method; or
214 * <li>Some other thread {@link Thread#interrupt interrupts} the current
215 * thread; or
216 * <li>The specified waiting time elapses.
217 * </ul>
218 * <p>If the count reaches zero then the method returns with the
219 * value <tt>true</tt>.
220 * <p>If the current thread:
221 * <ul>
222 * <li>has its interrupted status set on entry to this method; or
223 * <li>is {@link Thread#interrupt interrupted} while waiting,
224 * </ul>
225 * then {@link InterruptedException} is thrown and the current thread's
226 * interrupted status is cleared.
227 *
228 * <p>If the specified waiting time elapses then the value <tt>false</tt>
229 * is returned.
230 * If the time is
231 * less than or equal to zero, the method will not wait at all.
232 *
233 * @param timeout the maximum time to wait
234 * @param unit the time unit of the <tt>timeout</tt> argument.
235 * @return <tt>true</tt> if the count reached zero and <tt>false</tt>
236 * if the waiting time elapsed before the count reached zero.
237 *
238 * @throws InterruptedException if the current thread is interrupted
239 * while waiting.
240 */
241 public boolean await(long timeout, TimeUnit unit)
242 throws InterruptedException {
243 return sync.acquireSharedTimed(1, unit.toNanos(timeout));
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 sync.releaseShared(1);
257 }
258
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 return sync.getCount();
266 }
267 }