ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountDownLatch.java
Revision: 1.38
Committed: Wed Jun 8 00:50:35 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.37: +0 -1 lines
Log Message:
clean up imports

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 jsr166 1.37 * http://creativecommons.org/publicdomain/zero/1.0/
5 dl 1.2 */
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 jsr166 1.33 * <p>A {@code CountDownLatch} is initialized with a given <em>count</em>.
15     * The {@link #await await} methods block until the current count reaches
16     * zero due to invocations of the {@link #countDown} method, after which
17     * all waiting threads are released and any subsequent invocations of
18     * {@link #await await} return immediately. This is a one-shot phenomenon
19     * -- the count cannot be reset. If you need a version that resets the
20     * count, consider using a {@link CyclicBarrier}.
21 tim 1.1 *
22 jsr166 1.33 * <p>A {@code CountDownLatch} is a versatile synchronization tool
23 dl 1.5 * and can be used for a number of purposes. A
24 jsr166 1.33 * {@code CountDownLatch} initialized with a count of one serves as a
25 dholmes 1.9 * simple on/off latch, or gate: all threads invoking {@link #await await}
26 dl 1.5 * wait at the gate until it is opened by a thread invoking {@link
27 jsr166 1.33 * #countDown}. A {@code CountDownLatch} initialized to <em>N</em>
28 dl 1.5 * can be used to make one thread wait until <em>N</em> threads have
29     * completed some action, or some action has been completed N times.
30 jsr166 1.33 *
31     * <p>A useful property of a {@code CountDownLatch} is that it
32     * doesn't require that threads calling {@code countDown} wait for
33 dl 1.5 * 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 dl 1.35 * <p>Memory consistency effects: Until the count reaches
122     * zero, actions in a thread prior to calling
123 jsr166 1.31 * {@code countDown()}
124     * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
125 brian 1.29 * actions following a successful return from a corresponding
126 jsr166 1.31 * {@code await()} in another thread.
127 brian 1.29 *
128 tim 1.1 * @since 1.5
129 dl 1.5 * @author Doug Lea
130 tim 1.1 */
131     public class CountDownLatch {
132 dl 1.16 /**
133     * Synchronization control For CountDownLatch.
134     * Uses AQS state to represent count.
135     */
136     private static final class Sync extends AbstractQueuedSynchronizer {
137 dl 1.27 private static final long serialVersionUID = 4982264981922014374L;
138    
139 dl 1.16 Sync(int count) {
140 jsr166 1.25 setState(count);
141 dl 1.16 }
142 jsr166 1.25
143 dl 1.17 int getCount() {
144     return getState();
145     }
146    
147 jsr166 1.34 protected int tryAcquireShared(int acquires) {
148 jsr166 1.36 return (getState() == 0) ? 1 : -1;
149 dl 1.16 }
150 jsr166 1.25
151 jsr166 1.34 protected boolean tryReleaseShared(int releases) {
152 dl 1.16 // Decrement count; signal when transition to zero
153 dl 1.17 for (;;) {
154     int c = getState();
155     if (c == 0)
156     return false;
157 dl 1.19 int nextc = c-1;
158 jsr166 1.25 if (compareAndSetState(c, nextc))
159 dl 1.19 return nextc == 0;
160 dl 1.17 }
161 dl 1.16 }
162     }
163 tim 1.1
164 dl 1.16 private final Sync sync;
165 jsr166 1.33
166 tim 1.1 /**
167 jsr166 1.33 * Constructs a {@code CountDownLatch} initialized with the given count.
168 jsr166 1.25 *
169 tim 1.1 * @param count the number of times {@link #countDown} must be invoked
170 jsr166 1.33 * before threads can pass through {@link #await}
171     * @throws IllegalArgumentException if {@code count} is negative
172 tim 1.1 */
173 jsr166 1.25 public CountDownLatch(int count) {
174 dl 1.2 if (count < 0) throw new IllegalArgumentException("count < 0");
175 dl 1.16 this.sync = new Sync(count);
176 dl 1.2 }
177 tim 1.1
178     /**
179 jsr166 1.25 * Causes the current thread to wait until the latch has counted down to
180 jsr166 1.33 * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
181     *
182     * <p>If the current count is zero then this method returns immediately.
183 tim 1.1 *
184 jsr166 1.33 * <p>If the current count is greater than zero then the current
185     * thread becomes disabled for thread scheduling purposes and lies
186     * dormant until one of two things happen:
187 tim 1.1 * <ul>
188 dholmes 1.9 * <li>The count reaches zero due to invocations of the
189 tim 1.1 * {@link #countDown} method; or
190 jsr166 1.33 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
191     * the current thread.
192 tim 1.1 * </ul>
193 jsr166 1.33 *
194 tim 1.1 * <p>If the current thread:
195     * <ul>
196 jsr166 1.25 * <li>has its interrupted status set on entry to this method; or
197 jsr166 1.33 * <li>is {@linkplain Thread#interrupt interrupted} while waiting,
198 tim 1.1 * </ul>
199 jsr166 1.25 * then {@link InterruptedException} is thrown and the current thread's
200     * interrupted status is cleared.
201 tim 1.1 *
202     * @throws InterruptedException if the current thread is interrupted
203 jsr166 1.33 * while waiting
204 tim 1.1 */
205 dl 1.2 public void await() throws InterruptedException {
206 dl 1.16 sync.acquireSharedInterruptibly(1);
207 dl 1.2 }
208    
209 tim 1.1 /**
210 jsr166 1.25 * Causes the current thread to wait until the latch has counted down to
211 jsr166 1.33 * zero, unless the thread is {@linkplain Thread#interrupt interrupted},
212 tim 1.1 * or the specified waiting time elapses.
213     *
214 jsr166 1.33 * <p>If the current count is zero then this method returns immediately
215     * with the value {@code true}.
216 tim 1.1 *
217 jsr166 1.33 * <p>If the current count is greater than zero then the current
218     * thread becomes disabled for thread scheduling purposes and lies
219     * dormant until one of three things happen:
220 tim 1.1 * <ul>
221     * <li>The count reaches zero due to invocations of the
222     * {@link #countDown} method; or
223 jsr166 1.33 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
224     * the current thread; or
225 tim 1.1 * <li>The specified waiting time elapses.
226     * </ul>
227 jsr166 1.33 *
228 tim 1.1 * <p>If the count reaches zero then the method returns with the
229 jsr166 1.33 * value {@code true}.
230     *
231 tim 1.1 * <p>If the current thread:
232     * <ul>
233 jsr166 1.25 * <li>has its interrupted status set on entry to this method; or
234 jsr166 1.33 * <li>is {@linkplain Thread#interrupt interrupted} while waiting,
235 tim 1.1 * </ul>
236 jsr166 1.25 * then {@link InterruptedException} is thrown and the current thread's
237     * interrupted status is cleared.
238 tim 1.1 *
239 jsr166 1.33 * <p>If the specified waiting time elapses then the value {@code false}
240     * is returned. If the time is less than or equal to zero, the method
241     * will not wait at all.
242 tim 1.1 *
243     * @param timeout the maximum time to wait
244 jsr166 1.33 * @param unit the time unit of the {@code timeout} argument
245     * @return {@code true} if the count reached zero and {@code false}
246     * if the waiting time elapsed before the count reached zero
247 tim 1.1 * @throws InterruptedException if the current thread is interrupted
248 jsr166 1.33 * while waiting
249 tim 1.1 */
250 jsr166 1.25 public boolean await(long timeout, TimeUnit unit)
251 tim 1.1 throws InterruptedException {
252 dl 1.23 return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
253 tim 1.1 }
254    
255     /**
256     * Decrements the count of the latch, releasing all waiting threads if
257     * the count reaches zero.
258 jsr166 1.33 *
259     * <p>If the current count is greater than zero then it is decremented.
260     * If the new count is zero then all waiting threads are re-enabled for
261     * thread scheduling purposes.
262     *
263     * <p>If the current count equals zero then nothing happens.
264 tim 1.1 */
265 dl 1.2 public void countDown() {
266 dl 1.16 sync.releaseShared(1);
267 dl 1.2 }
268 tim 1.1
269     /**
270     * Returns the current count.
271 jsr166 1.33 *
272 tim 1.1 * <p>This method is typically used for debugging and testing purposes.
273 jsr166 1.33 *
274     * @return the current count
275 tim 1.1 */
276     public long getCount() {
277 dl 1.17 return sync.getCount();
278 tim 1.1 }
279 dl 1.21
280     /**
281 dl 1.24 * Returns a string identifying this latch, as well as its state.
282 jsr166 1.33 * The state, in brackets, includes the String {@code "Count ="}
283     * followed by the current count.
284     *
285     * @return a string identifying this latch, as well as its state
286 dl 1.21 */
287     public String toString() {
288     return super.toString() + "[Count = " + sync.getCount() + "]";
289     }
290 tim 1.1 }