ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountDownLatch.java
Revision: 1.45
Committed: Fri Nov 27 17:41:59 2020 UTC (3 years, 6 months ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.44: +3 -5 lines
Log Message:
Incorporate snippets code improvements from Pavel Rappo

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 jsr166 1.43
9 jsr166 1.40 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
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 jsr166 1.44 * <pre> {@code
48 tim 1.1 * 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 jsr166 1.41 * this.startSignal = startSignal;
68     * this.doneSignal = doneSignal;
69 tim 1.1 * }
70     * public void run() {
71 jsr166 1.41 * try {
72     * startSignal.await();
73     * doWork();
74     * doneSignal.countDown();
75     * } catch (InterruptedException ex) {} // return;
76 tim 1.1 * }
77     *
78     * void doWork() { ... }
79 jsr166 1.39 * }}</pre>
80 tim 1.1 *
81 dl 1.5 * <p>Another typical usage would be to divide a problem into N parts,
82     * describe each part with a Runnable that executes that portion and
83     * counts down on the latch, and queue all the Runnables to an
84     * Executor. When all sub-parts are complete, the coordinating thread
85 dl 1.13 * will be able to pass through await. (When threads must repeatedly
86     * count down in this way, instead use a {@link CyclicBarrier}.)
87 brian 1.4 *
88 jsr166 1.44 * <pre> {@code
89 brian 1.4 * class Driver2 { // ...
90     * void main() throws InterruptedException {
91     * CountDownLatch doneSignal = new CountDownLatch(N);
92 dl 1.45 * Executor e = ...;
93 brian 1.4 *
94     * for (int i = 0; i < N; ++i) // create and start threads
95     * e.execute(new WorkerRunnable(doneSignal, i));
96     *
97     * doneSignal.await(); // wait for all to finish
98     * }
99     * }
100     *
101     * class WorkerRunnable implements Runnable {
102     * private final CountDownLatch doneSignal;
103     * private final int i;
104 dl 1.13 * WorkerRunnable(CountDownLatch doneSignal, int i) {
105 jsr166 1.41 * this.doneSignal = doneSignal;
106     * this.i = i;
107 brian 1.4 * }
108     * public void run() {
109 dl 1.45 * doWork();
110     * doneSignal.countDown();
111 brian 1.4 * }
112     *
113     * void doWork() { ... }
114 jsr166 1.39 * }}</pre>
115 brian 1.4 *
116 dl 1.35 * <p>Memory consistency effects: Until the count reaches
117     * zero, actions in a thread prior to calling
118 jsr166 1.31 * {@code countDown()}
119     * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
120 brian 1.29 * actions following a successful return from a corresponding
121 jsr166 1.31 * {@code await()} in another thread.
122 brian 1.29 *
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 jsr166 1.34 protected int tryAcquireShared(int acquires) {
143 jsr166 1.36 return (getState() == 0) ? 1 : -1;
144 dl 1.16 }
145 jsr166 1.25
146 jsr166 1.34 protected 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 jsr166 1.42 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 jsr166 1.33
161 tim 1.1 /**
162 jsr166 1.33 * Constructs a {@code CountDownLatch} initialized with the given count.
163 jsr166 1.25 *
164 tim 1.1 * @param count the number of times {@link #countDown} must be invoked
165 jsr166 1.33 * before threads can pass through {@link #await}
166     * @throws IllegalArgumentException if {@code count} is negative
167 tim 1.1 */
168 jsr166 1.25 public CountDownLatch(int count) {
169 dl 1.2 if (count < 0) throw new IllegalArgumentException("count < 0");
170 dl 1.16 this.sync = new Sync(count);
171 dl 1.2 }
172 tim 1.1
173     /**
174 jsr166 1.25 * Causes the current thread to wait until the latch has counted down to
175 jsr166 1.33 * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
176     *
177     * <p>If the current count is zero then this method returns immediately.
178 tim 1.1 *
179 jsr166 1.33 * <p>If the current count is greater than zero then the current
180     * thread becomes disabled for thread scheduling purposes and lies
181     * dormant until one of two things happen:
182 tim 1.1 * <ul>
183 dholmes 1.9 * <li>The count reaches zero due to invocations of the
184 tim 1.1 * {@link #countDown} method; or
185 jsr166 1.33 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
186     * the current thread.
187 tim 1.1 * </ul>
188 jsr166 1.33 *
189 tim 1.1 * <p>If the current thread:
190     * <ul>
191 jsr166 1.25 * <li>has its interrupted status set on entry to this method; or
192 jsr166 1.33 * <li>is {@linkplain 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 jsr166 1.33 * while waiting
199 tim 1.1 */
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 jsr166 1.33 * zero, unless the thread is {@linkplain Thread#interrupt interrupted},
207 tim 1.1 * or the specified waiting time elapses.
208     *
209 jsr166 1.33 * <p>If the current count is zero then this method returns immediately
210     * with the value {@code true}.
211 tim 1.1 *
212 jsr166 1.33 * <p>If the current count is greater than zero then the current
213     * thread becomes disabled for thread scheduling purposes and lies
214     * dormant until one of three things happen:
215 tim 1.1 * <ul>
216     * <li>The count reaches zero due to invocations of the
217     * {@link #countDown} method; or
218 jsr166 1.33 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
219     * the current thread; or
220 tim 1.1 * <li>The specified waiting time elapses.
221     * </ul>
222 jsr166 1.33 *
223 tim 1.1 * <p>If the count reaches zero then the method returns with the
224 jsr166 1.33 * value {@code true}.
225     *
226 tim 1.1 * <p>If the current thread:
227     * <ul>
228 jsr166 1.25 * <li>has its interrupted status set on entry to this method; or
229 jsr166 1.33 * <li>is {@linkplain Thread#interrupt interrupted} while waiting,
230 tim 1.1 * </ul>
231 jsr166 1.25 * then {@link InterruptedException} is thrown and the current thread's
232     * interrupted status is cleared.
233 tim 1.1 *
234 jsr166 1.33 * <p>If the specified waiting time elapses then the value {@code false}
235     * is returned. If the time is less than or equal to zero, the method
236     * will not wait at all.
237 tim 1.1 *
238     * @param timeout the maximum time to wait
239 jsr166 1.33 * @param unit the time unit of the {@code timeout} argument
240     * @return {@code true} if the count reached zero and {@code false}
241     * if the waiting time elapsed before the count reached zero
242 tim 1.1 * @throws InterruptedException if the current thread is interrupted
243 jsr166 1.33 * while waiting
244 tim 1.1 */
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 jsr166 1.33 *
254     * <p>If the current count is greater than zero then it is decremented.
255     * If the new count is zero then all waiting threads are re-enabled for
256     * thread scheduling purposes.
257     *
258     * <p>If the current count equals zero then nothing happens.
259 tim 1.1 */
260 dl 1.2 public void countDown() {
261 dl 1.16 sync.releaseShared(1);
262 dl 1.2 }
263 tim 1.1
264     /**
265     * Returns the current count.
266 jsr166 1.33 *
267 tim 1.1 * <p>This method is typically used for debugging and testing purposes.
268 jsr166 1.33 *
269     * @return the current count
270 tim 1.1 */
271     public long getCount() {
272 dl 1.17 return sync.getCount();
273 tim 1.1 }
274 dl 1.21
275     /**
276 dl 1.24 * Returns a string identifying this latch, as well as its state.
277 jsr166 1.33 * The state, in brackets, includes the String {@code "Count ="}
278     * followed by the current count.
279     *
280     * @return a string identifying this latch, as well as its state
281 dl 1.21 */
282     public String toString() {
283     return super.toString() + "[Count = " + sync.getCount() + "]";
284     }
285 tim 1.1 }