ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountDownLatch.java
Revision: 1.18
Committed: Fri Jan 2 21:02:31 2004 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.17: +2 -2 lines
Log Message:
Avoid timeout problems in fair modes; improve AQS method names

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.18 public int tryAcquireShared(boolean isQueued, 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     if (compareAndSetState(c, c-1))
150     return c == 1;
151     }
152 dl 1.16 }
153     }
154 tim 1.1
155 dl 1.16 private final Sync sync;
156 tim 1.1 /**
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 dl 1.2 * @throws IllegalArgumentException if <tt>count</tt> is less than zero.
164 tim 1.1 */
165 dl 1.2 public CountDownLatch(int count) {
166     if (count < 0) throw new IllegalArgumentException("count < 0");
167 dl 1.16 this.sync = new Sync(count);
168 dl 1.2 }
169 tim 1.1
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 dholmes 1.9 * <li>The count reaches zero due to invocations of the
181 tim 1.1 * {@link #countDown} method; or
182 dholmes 1.9 * <li>Some other thread {@link Thread#interrupt interrupts} the current
183 tim 1.1 * 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 dl 1.2 public void await() throws InterruptedException {
197 dl 1.16 sync.acquireSharedInterruptibly(1);
198 dl 1.2 }
199    
200 tim 1.1 /**
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 dholmes 1.10 * If the time is
231 tim 1.1 * less than or equal to zero, the method will not wait at all.
232     *
233     * @param timeout the maximum time to wait
234 dl 1.2 * @param unit the time unit of the <tt>timeout</tt> argument.
235 tim 1.1 * @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 dl 1.2 public boolean await(long timeout, TimeUnit unit)
242 tim 1.1 throws InterruptedException {
243 dl 1.16 return sync.acquireSharedTimed(1, unit.toNanos(timeout));
244 tim 1.1 }
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 dl 1.2 public void countDown() {
256 dl 1.16 sync.releaseShared(1);
257 dl 1.2 }
258 tim 1.1
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 dl 1.17 return sync.getCount();
266 tim 1.1 }
267     }