ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountDownLatch.java
Revision: 1.36
Committed: Mon Nov 29 20:58:06 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.35: +1 -1 lines
Log Message:
consistent ternary operator style

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