ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountDownLatch.java
Revision: 1.28
Committed: Wed Aug 24 04:58:20 2005 UTC (18 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.27: +1 -0 lines
Log Message:
workaround for 6280605

File Contents

# User Rev Content
1 dl 1.2 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.16 * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/licenses/publicdomain
5 dl 1.2 */
6    
7 tim 1.1 package java.util.concurrent;
8 jsr166 1.28 import java.util.concurrent.*; // for javadoc (till 6280605 is fixed)
9 dl 1.6 import java.util.concurrent.locks.*;
10 dl 1.16 import java.util.concurrent.atomic.*;
11 tim 1.1
12     /**
13 brian 1.4 * A synchronization aid that allows one or more threads to wait until
14     * a set of operations being performed in other threads completes.
15 dl 1.3 *
16     * <p>A <tt>CountDownLatch</tt> is initialized with a given
17 dholmes 1.9 * <em>count</em>. The {@link #await await} methods block until the current
18 dl 1.3 * {@link #getCount count} reaches zero due to invocations of the
19     * {@link #countDown} method, after which all waiting threads are
20 dholmes 1.9 * released and any subsequent invocations of {@link #await await} return
21 dl 1.3 * immediately. This is a one-shot phenomenon -- the count cannot be
22     * reset. If you need a version that resets the count, consider using
23     * a {@link CyclicBarrier}.
24 tim 1.1 *
25     * <p>A <tt>CountDownLatch</tt> is a versatile synchronization tool
26 dl 1.5 * and can be used for a number of purposes. A
27     * <tt>CountDownLatch</tt> initialized with a count of one serves as a
28 dholmes 1.9 * simple on/off latch, or gate: all threads invoking {@link #await await}
29 dl 1.5 * wait at the gate until it is opened by a thread invoking {@link
30     * #countDown}. A <tt>CountDownLatch</tt> initialized to <em>N</em>
31     * can be used to make one thread wait until <em>N</em> threads have
32     * completed some action, or some action has been completed N times.
33     * <p>A useful property of a <tt>CountDownLatch</tt> is that it
34     * doesn't require that threads calling <tt>countDown</tt> wait for
35     * the count to reach zero before proceeding, it simply prevents any
36 dholmes 1.9 * thread from proceeding past an {@link #await await} until all
37 dl 1.5 * threads could pass.
38 tim 1.1 *
39     * <p><b>Sample usage:</b> Here is a pair of classes in which a group
40     * of worker threads use two countdown latches:
41     * <ul>
42 dholmes 1.9 * <li>The first is a start signal that prevents any worker from proceeding
43 tim 1.1 * until the driver is ready for them to proceed;
44 dholmes 1.9 * <li>The second is a completion signal that allows the driver to wait
45 tim 1.1 * until all workers have completed.
46     * </ul>
47     *
48     * <pre>
49     * class Driver { // ...
50     * void main() throws InterruptedException {
51     * CountDownLatch startSignal = new CountDownLatch(1);
52     * CountDownLatch doneSignal = new CountDownLatch(N);
53     *
54     * for (int i = 0; i < N; ++i) // create and start threads
55     * new Thread(new Worker(startSignal, doneSignal)).start();
56     *
57     * doSomethingElse(); // don't let run yet
58     * startSignal.countDown(); // let all threads proceed
59     * doSomethingElse();
60     * doneSignal.await(); // wait for all to finish
61     * }
62     * }
63     *
64     * class Worker implements Runnable {
65     * private final CountDownLatch startSignal;
66     * private final CountDownLatch doneSignal;
67     * Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
68     * this.startSignal = startSignal;
69     * this.doneSignal = doneSignal;
70     * }
71     * public void run() {
72     * try {
73     * startSignal.await();
74     * doWork();
75     * doneSignal.countDown();
76 tim 1.7 * } catch (InterruptedException ex) {} // return;
77 tim 1.1 * }
78     *
79     * void doWork() { ... }
80     * }
81     *
82     * </pre>
83     *
84 dl 1.5 * <p>Another typical usage would be to divide a problem into N parts,
85     * describe each part with a Runnable that executes that portion and
86     * counts down on the latch, and queue all the Runnables to an
87     * Executor. When all sub-parts are complete, the coordinating thread
88 dl 1.13 * will be able to pass through await. (When threads must repeatedly
89     * count down in this way, instead use a {@link CyclicBarrier}.)
90 brian 1.4 *
91     * <pre>
92     * class Driver2 { // ...
93     * void main() throws InterruptedException {
94     * CountDownLatch doneSignal = new CountDownLatch(N);
95     * Executor e = ...
96     *
97     * for (int i = 0; i < N; ++i) // create and start threads
98     * e.execute(new WorkerRunnable(doneSignal, i));
99     *
100     * doneSignal.await(); // wait for all to finish
101     * }
102     * }
103     *
104     * class WorkerRunnable implements Runnable {
105     * private final CountDownLatch doneSignal;
106     * private final int i;
107 dl 1.13 * WorkerRunnable(CountDownLatch doneSignal, int i) {
108 brian 1.4 * this.doneSignal = doneSignal;
109     * this.i = i;
110     * }
111     * public void run() {
112     * try {
113     * doWork(i);
114     * doneSignal.countDown();
115 tim 1.7 * } catch (InterruptedException ex) {} // return;
116 brian 1.4 * }
117     *
118     * void doWork() { ... }
119     * }
120     *
121     * </pre>
122     *
123 tim 1.1 * @since 1.5
124 dl 1.5 * @author Doug Lea
125 tim 1.1 */
126     public class CountDownLatch {
127 dl 1.16 /**
128     * Synchronization control For CountDownLatch.
129     * Uses AQS state to represent count.
130     */
131     private static final class Sync extends AbstractQueuedSynchronizer {
132 dl 1.27 private static final long serialVersionUID = 4982264981922014374L;
133    
134 dl 1.16 Sync(int count) {
135 jsr166 1.25 setState(count);
136 dl 1.16 }
137 jsr166 1.25
138 dl 1.17 int getCount() {
139     return getState();
140     }
141    
142 dl 1.19 public int tryAcquireShared(int acquires) {
143 dl 1.17 return getState() == 0? 1 : -1;
144 dl 1.16 }
145 jsr166 1.25
146 dl 1.18 public boolean tryReleaseShared(int releases) {
147 dl 1.16 // Decrement count; signal when transition to zero
148 dl 1.17 for (;;) {
149     int c = getState();
150     if (c == 0)
151     return false;
152 dl 1.19 int nextc = c-1;
153 jsr166 1.25 if (compareAndSetState(c, nextc))
154 dl 1.19 return nextc == 0;
155 dl 1.17 }
156 dl 1.16 }
157     }
158 tim 1.1
159 dl 1.16 private final Sync sync;
160 tim 1.1 /**
161     * Constructs a <tt>CountDownLatch</tt> initialized with the given
162     * count.
163 jsr166 1.25 *
164 tim 1.1 * @param count the number of times {@link #countDown} must be invoked
165     * before threads can pass through {@link #await}.
166     *
167 dl 1.2 * @throws IllegalArgumentException if <tt>count</tt> is less than zero.
168 tim 1.1 */
169 jsr166 1.25 public CountDownLatch(int count) {
170 dl 1.2 if (count < 0) throw new IllegalArgumentException("count < 0");
171 dl 1.16 this.sync = new Sync(count);
172 dl 1.2 }
173 tim 1.1
174     /**
175 jsr166 1.25 * Causes the current thread to wait until the latch has counted down to
176 tim 1.1 * zero, unless the thread is {@link Thread#interrupt interrupted}.
177     *
178     * <p>If the current {@link #getCount count} is zero then this method
179     * returns immediately.
180     * <p>If the current {@link #getCount count} is greater than zero then
181 jsr166 1.25 * the current thread becomes disabled for thread scheduling
182 tim 1.1 * purposes and lies dormant until one of two things happen:
183     * <ul>
184 dholmes 1.9 * <li>The count reaches zero due to invocations of the
185 tim 1.1 * {@link #countDown} method; or
186 dholmes 1.9 * <li>Some other thread {@link Thread#interrupt interrupts} the current
187 tim 1.1 * thread.
188     * </ul>
189     * <p>If the current thread:
190     * <ul>
191 jsr166 1.25 * <li>has its interrupted status set on entry to this method; or
192     * <li>is {@link Thread#interrupt interrupted} while waiting,
193 tim 1.1 * </ul>
194 jsr166 1.25 * then {@link InterruptedException} is thrown and the current thread's
195     * interrupted status is cleared.
196 tim 1.1 *
197     * @throws InterruptedException if the current thread is interrupted
198     * while waiting.
199     */
200 dl 1.2 public void await() throws InterruptedException {
201 dl 1.16 sync.acquireSharedInterruptibly(1);
202 dl 1.2 }
203    
204 tim 1.1 /**
205 jsr166 1.25 * Causes the current thread to wait until the latch has counted down to
206 tim 1.1 * zero, unless the thread is {@link Thread#interrupt interrupted},
207     * or the specified waiting time elapses.
208     *
209     * <p>If the current {@link #getCount count} is zero then this method
210     * returns immediately with the value <tt>true</tt>.
211     *
212     * <p>If the current {@link #getCount count} is greater than zero then
213 jsr166 1.25 * the current thread becomes disabled for thread scheduling
214 tim 1.1 * purposes and lies dormant until one of three things happen:
215     * <ul>
216     * <li>The count reaches zero due to invocations of the
217     * {@link #countDown} method; or
218     * <li>Some other thread {@link Thread#interrupt interrupts} the current
219     * thread; or
220     * <li>The specified waiting time elapses.
221     * </ul>
222     * <p>If the count reaches zero then the method returns with the
223     * value <tt>true</tt>.
224     * <p>If the current thread:
225     * <ul>
226 jsr166 1.25 * <li>has its interrupted status set on entry to this method; or
227     * <li>is {@link Thread#interrupt interrupted} while waiting,
228 tim 1.1 * </ul>
229 jsr166 1.25 * then {@link InterruptedException} is thrown and the current thread's
230     * interrupted status is cleared.
231 tim 1.1 *
232     * <p>If the specified waiting time elapses then the value <tt>false</tt>
233     * is returned.
234 jsr166 1.25 * If the time is
235 tim 1.1 * less than or equal to zero, the method will not wait at all.
236     *
237     * @param timeout the maximum time to wait
238 dl 1.2 * @param unit the time unit of the <tt>timeout</tt> argument.
239 jsr166 1.26 * @return <tt>true</tt> if the count reached zero and <tt>false</tt>
240 tim 1.1 * if the waiting time elapsed before the count reached zero.
241     *
242     * @throws InterruptedException if the current thread is interrupted
243     * while waiting.
244     */
245 jsr166 1.25 public boolean await(long timeout, TimeUnit unit)
246 tim 1.1 throws InterruptedException {
247 dl 1.23 return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
248 tim 1.1 }
249    
250     /**
251     * Decrements the count of the latch, releasing all waiting threads if
252     * the count reaches zero.
253     * <p>If the current {@link #getCount count} is greater than zero then
254     * it is decremented. If the new count is zero then all waiting threads
255     * are re-enabled for thread scheduling purposes.
256     * <p>If the current {@link #getCount count} equals zero then nothing
257     * happens.
258     */
259 dl 1.2 public void countDown() {
260 dl 1.16 sync.releaseShared(1);
261 dl 1.2 }
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.17 return sync.getCount();
270 tim 1.1 }
271 dl 1.21
272     /**
273 dl 1.24 * Returns a string identifying this latch, as well as its state.
274 jsr166 1.25 * The state, in brackets, includes the String
275 dl 1.22 * &quot;Count =&quot; followed by the current count.
276     * @return a string identifying this latch, as well as its
277     * state
278 dl 1.21 */
279     public String toString() {
280     return super.toString() + "[Count = " + sync.getCount() + "]";
281     }
282    
283 tim 1.1 }