ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountDownLatch.java
Revision: 1.22
Committed: Sat Jan 10 20:37:03 2004 UTC (20 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.21: +5 -2 lines
Log Message:
Document toString

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     * <p>A <tt>CountDownLatch</tt> is initialized with a given
16 dholmes 1.9 * <em>count</em>. The {@link #await await} methods block until the current
17 dl 1.3 * {@link #getCount count} reaches zero due to invocations of the
18     * {@link #countDown} method, after which all waiting threads are
19 dholmes 1.9 * released and any subsequent invocations of {@link #await await} return
20 dl 1.3 * 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 tim 1.1 *
24     * <p>A <tt>CountDownLatch</tt> is a versatile synchronization tool
25 dl 1.5 * and can be used for a number of purposes. A
26     * <tt>CountDownLatch</tt> initialized with a count of one serves as a
27 dholmes 1.9 * simple on/off latch, or gate: all threads invoking {@link #await await}
28 dl 1.5 * 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 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 tim 1.1 * @since 1.5
123 dl 1.5 * @author Doug Lea
124 tim 1.1 */
125     public class CountDownLatch {
126 dl 1.16 /**
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 dl 1.17 setState(count);
133 dl 1.16 }
134    
135 dl 1.17 int getCount() {
136     return getState();
137     }
138    
139 dl 1.19 public int tryAcquireShared(int acquires) {
140 dl 1.17 return getState() == 0? 1 : -1;
141 dl 1.16 }
142    
143 dl 1.18 public boolean tryReleaseShared(int releases) {
144 dl 1.16 // Decrement count; signal when transition to zero
145 dl 1.17 for (;;) {
146     int c = getState();
147     if (c == 0)
148     return false;
149 dl 1.19 int nextc = c-1;
150     if (compareAndSetState(c, nextc))
151     return nextc == 0;
152 dl 1.17 }
153 dl 1.16 }
154     }
155 tim 1.1
156 dl 1.16 private final Sync sync;
157 tim 1.1 /**
158     * Constructs a <tt>CountDownLatch</tt> initialized with the given
159     * count.
160     *
161     * @param count the number of times {@link #countDown} must be invoked
162     * before threads can pass through {@link #await}.
163     *
164 dl 1.2 * @throws IllegalArgumentException if <tt>count</tt> is less than zero.
165 tim 1.1 */
166 dl 1.2 public CountDownLatch(int count) {
167     if (count < 0) throw new IllegalArgumentException("count < 0");
168 dl 1.16 this.sync = new Sync(count);
169 dl 1.2 }
170 tim 1.1
171     /**
172     * Causes the current thread to wait until the latch has counted down to
173     * zero, unless the thread is {@link Thread#interrupt interrupted}.
174     *
175     * <p>If the current {@link #getCount count} is zero then this method
176     * returns immediately.
177     * <p>If the current {@link #getCount count} is greater than zero then
178     * the current thread becomes disabled for thread scheduling
179     * purposes and lies dormant until one of two things happen:
180     * <ul>
181 dholmes 1.9 * <li>The count reaches zero due to invocations of the
182 tim 1.1 * {@link #countDown} method; or
183 dholmes 1.9 * <li>Some other thread {@link Thread#interrupt interrupts} the current
184 tim 1.1 * thread.
185     * </ul>
186     * <p>If the current thread:
187     * <ul>
188     * <li>has its interrupted status set on entry to this method; or
189     * <li>is {@link Thread#interrupt interrupted} while waiting,
190     * </ul>
191     * then {@link InterruptedException} is thrown and the current thread's
192     * interrupted status is cleared.
193     *
194     * @throws InterruptedException if the current thread is interrupted
195     * while waiting.
196     */
197 dl 1.2 public void await() throws InterruptedException {
198 dl 1.16 sync.acquireSharedInterruptibly(1);
199 dl 1.2 }
200    
201 tim 1.1 /**
202     * Causes the current thread to wait until the latch has counted down to
203     * zero, unless the thread is {@link Thread#interrupt interrupted},
204     * or the specified waiting time elapses.
205     *
206     * <p>If the current {@link #getCount count} is zero then this method
207     * returns immediately with the value <tt>true</tt>.
208     *
209     * <p>If the current {@link #getCount count} is greater than zero then
210     * the current thread becomes disabled for thread scheduling
211     * purposes and lies dormant until one of three things happen:
212     * <ul>
213     * <li>The count reaches zero due to invocations of the
214     * {@link #countDown} method; or
215     * <li>Some other thread {@link Thread#interrupt interrupts} the current
216     * thread; or
217     * <li>The specified waiting time elapses.
218     * </ul>
219     * <p>If the count reaches zero then the method returns with the
220     * value <tt>true</tt>.
221     * <p>If the current thread:
222     * <ul>
223     * <li>has its interrupted status set on entry to this method; or
224     * <li>is {@link Thread#interrupt interrupted} while waiting,
225     * </ul>
226     * then {@link InterruptedException} is thrown and the current thread's
227     * interrupted status is cleared.
228     *
229     * <p>If the specified waiting time elapses then the value <tt>false</tt>
230     * is returned.
231 dholmes 1.10 * If the time is
232 tim 1.1 * less than or equal to zero, the method will not wait at all.
233     *
234     * @param timeout the maximum time to wait
235 dl 1.2 * @param unit the time unit of the <tt>timeout</tt> argument.
236 tim 1.1 * @return <tt>true</tt> if the count reached zero and <tt>false</tt>
237     * if the waiting time elapsed before the count reached zero.
238     *
239     * @throws InterruptedException if the current thread is interrupted
240     * while waiting.
241     */
242 dl 1.2 public boolean await(long timeout, TimeUnit unit)
243 tim 1.1 throws InterruptedException {
244 dl 1.20 return sync.acquireSharedNanos(1, unit.toNanos(timeout));
245 tim 1.1 }
246    
247     /**
248     * Decrements the count of the latch, releasing all waiting threads if
249     * the count reaches zero.
250     * <p>If the current {@link #getCount count} is greater than zero then
251     * it is decremented. If the new count is zero then all waiting threads
252     * are re-enabled for thread scheduling purposes.
253     * <p>If the current {@link #getCount count} equals zero then nothing
254     * happens.
255     */
256 dl 1.2 public void countDown() {
257 dl 1.16 sync.releaseShared(1);
258 dl 1.2 }
259 tim 1.1
260     /**
261     * Returns the current count.
262     * <p>This method is typically used for debugging and testing purposes.
263     * @return the current count.
264     */
265     public long getCount() {
266 dl 1.17 return sync.getCount();
267 tim 1.1 }
268 dl 1.21
269     /**
270 dl 1.22 * Returns a string identifying this latch, as well its state.
271     * The state, in brackets, includes the String
272     * &quot;Count =&quot; followed by the current count.
273     * @return a string identifying this latch, as well as its
274     * state
275 dl 1.21 */
276     public String toString() {
277     return super.toString() + "[Count = " + sync.getCount() + "]";
278     }
279    
280 tim 1.1 }