001 /*
002 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
003 *
004 * This code is free software; you can redistribute it and/or modify it
005 * under the terms of the GNU General Public License version 2 only, as
006 * published by the Free Software Foundation. Sun designates this
007 * particular file as subject to the "Classpath" exception as provided
008 * by Sun in the LICENSE file that accompanied this code.
009 *
010 * This code is distributed in the hope that it will be useful, but WITHOUT
011 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
012 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
013 * version 2 for more details (a copy is included in the LICENSE file that
014 * accompanied this code).
015 *
016 * You should have received a copy of the GNU General Public License version
017 * 2 along with this work; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
019 *
020 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
021 * CA 95054 USA or visit www.sun.com if you need additional information or
022 * have any questions.
023 */
024
025 /*
026 * This file is available under and governed by the GNU General Public
027 * License version 2 only, as published by the Free Software Foundation.
028 * However, the following notice accompanied the original version of this
029 * file:
030 *
031 * Written by Doug Lea with assistance from members of JCP JSR-166
032 * Expert Group and released to the public domain, as explained at
033 * http://creativecommons.org/licenses/publicdomain
034 */
035
036 package java.util.concurrent;
037
038 import java.util.concurrent.locks.*;
039 import java.util.concurrent.atomic.*;
040
041 /**
042 * A synchronization aid that allows one or more threads to wait until
043 * a set of operations being performed in other threads completes.
044 *
045 * <p>A {@code CountDownLatch} is initialized with a given <em>count</em>.
046 * The {@link #await await} methods block until the current count reaches
047 * zero due to invocations of the {@link #countDown} method, after which
048 * all waiting threads are released and any subsequent invocations of
049 * {@link #await await} return immediately. This is a one-shot phenomenon
050 * -- the count cannot be reset. If you need a version that resets the
051 * count, consider using a {@link CyclicBarrier}.
052 *
053 * <p>A {@code CountDownLatch} is a versatile synchronization tool
054 * and can be used for a number of purposes. A
055 * {@code CountDownLatch} initialized with a count of one serves as a
056 * simple on/off latch, or gate: all threads invoking {@link #await await}
057 * wait at the gate until it is opened by a thread invoking {@link
058 * #countDown}. A {@code CountDownLatch} initialized to <em>N</em>
059 * can be used to make one thread wait until <em>N</em> threads have
060 * completed some action, or some action has been completed N times.
061 *
062 * <p>A useful property of a {@code CountDownLatch} is that it
063 * doesn't require that threads calling {@code countDown} wait for
064 * the count to reach zero before proceeding, it simply prevents any
065 * thread from proceeding past an {@link #await await} until all
066 * threads could pass.
067 *
068 * <p><b>Sample usage:</b> Here is a pair of classes in which a group
069 * of worker threads use two countdown latches:
070 * <ul>
071 * <li>The first is a start signal that prevents any worker from proceeding
072 * until the driver is ready for them to proceed;
073 * <li>The second is a completion signal that allows the driver to wait
074 * until all workers have completed.
075 * </ul>
076 *
077 * <pre>
078 * class Driver { // ...
079 * void main() throws InterruptedException {
080 * CountDownLatch startSignal = new CountDownLatch(1);
081 * CountDownLatch doneSignal = new CountDownLatch(N);
082 *
083 * for (int i = 0; i < N; ++i) // create and start threads
084 * new Thread(new Worker(startSignal, doneSignal)).start();
085 *
086 * doSomethingElse(); // don't let run yet
087 * startSignal.countDown(); // let all threads proceed
088 * doSomethingElse();
089 * doneSignal.await(); // wait for all to finish
090 * }
091 * }
092 *
093 * class Worker implements Runnable {
094 * private final CountDownLatch startSignal;
095 * private final CountDownLatch doneSignal;
096 * Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
097 * this.startSignal = startSignal;
098 * this.doneSignal = doneSignal;
099 * }
100 * public void run() {
101 * try {
102 * startSignal.await();
103 * doWork();
104 * doneSignal.countDown();
105 * } catch (InterruptedException ex) {} // return;
106 * }
107 *
108 * void doWork() { ... }
109 * }
110 *
111 * </pre>
112 *
113 * <p>Another typical usage would be to divide a problem into N parts,
114 * describe each part with a Runnable that executes that portion and
115 * counts down on the latch, and queue all the Runnables to an
116 * Executor. When all sub-parts are complete, the coordinating thread
117 * will be able to pass through await. (When threads must repeatedly
118 * count down in this way, instead use a {@link CyclicBarrier}.)
119 *
120 * <pre>
121 * class Driver2 { // ...
122 * void main() throws InterruptedException {
123 * CountDownLatch doneSignal = new CountDownLatch(N);
124 * Executor e = ...
125 *
126 * for (int i = 0; i < N; ++i) // create and start threads
127 * e.execute(new WorkerRunnable(doneSignal, i));
128 *
129 * doneSignal.await(); // wait for all to finish
130 * }
131 * }
132 *
133 * class WorkerRunnable implements Runnable {
134 * private final CountDownLatch doneSignal;
135 * private final int i;
136 * WorkerRunnable(CountDownLatch doneSignal, int i) {
137 * this.doneSignal = doneSignal;
138 * this.i = i;
139 * }
140 * public void run() {
141 * try {
142 * doWork(i);
143 * doneSignal.countDown();
144 * } catch (InterruptedException ex) {} // return;
145 * }
146 *
147 * void doWork() { ... }
148 * }
149 *
150 * </pre>
151 *
152 * <p>Memory consistency effects: Actions in a thread prior to calling
153 * {@code countDown()}
154 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
155 * actions following a successful return from a corresponding
156 * {@code await()} in another thread.
157 *
158 * @since 1.5
159 * @author Doug Lea
160 */
161 public class CountDownLatch {
162 /**
163 * Synchronization control For CountDownLatch.
164 * Uses AQS state to represent count.
165 */
166 private static final class Sync extends AbstractQueuedSynchronizer {
167 private static final long serialVersionUID = 4982264981922014374L;
168
169 Sync(int count) {
170 setState(count);
171 }
172
173 int getCount() {
174 return getState();
175 }
176
177 protected int tryAcquireShared(int acquires) {
178 return getState() == 0 ? 1 : -1;
179 }
180
181 protected boolean tryReleaseShared(int releases) {
182 // Decrement count; signal when transition to zero
183 for (;;) {
184 int c = getState();
185 if (c == 0)
186 return false;
187 int nextc = c - 1;
188 if (compareAndSetState(c, nextc))
189 return nextc == 0;
190 }
191 }
192 }
193
194 private final Sync sync;
195
196 /**
197 * Constructs a {@code CountDownLatch} initialized with the given count.
198 *
199 * @param count the number of times {@link #countDown} must be invoked
200 * before threads can pass through {@link #await}
201 * @throws IllegalArgumentException if {@code count} is negative
202 */
203 public CountDownLatch(int count) {
204 if (count < 0)
205 throw new IllegalArgumentException("count < 0");
206 this .sync = new Sync(count);
207 }
208
209 /**
210 * Causes the current thread to wait until the latch has counted down to
211 * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
212 *
213 * <p>If the current count is zero then this method returns immediately.
214 *
215 * <p>If the current count is greater than zero then the current
216 * thread becomes disabled for thread scheduling purposes and lies
217 * dormant until one of two things happen:
218 * <ul>
219 * <li>The count reaches zero due to invocations of the
220 * {@link #countDown} method; or
221 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
222 * the current thread.
223 * </ul>
224 *
225 * <p>If the current thread:
226 * <ul>
227 * <li>has its interrupted status set on entry to this method; or
228 * <li>is {@linkplain Thread#interrupt interrupted} while waiting,
229 * </ul>
230 * then {@link InterruptedException} is thrown and the current thread's
231 * interrupted status is cleared.
232 *
233 * @throws InterruptedException if the current thread is interrupted
234 * while waiting
235 */
236 public void await() throws InterruptedException {
237 sync.acquireSharedInterruptibly(1);
238 }
239
240 /**
241 * Causes the current thread to wait until the latch has counted down to
242 * zero, unless the thread is {@linkplain Thread#interrupt interrupted},
243 * or the specified waiting time elapses.
244 *
245 * <p>If the current count is zero then this method returns immediately
246 * with the value {@code true}.
247 *
248 * <p>If the current count is greater than zero then the current
249 * thread becomes disabled for thread scheduling purposes and lies
250 * dormant until one of three things happen:
251 * <ul>
252 * <li>The count reaches zero due to invocations of the
253 * {@link #countDown} method; or
254 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
255 * the current thread; or
256 * <li>The specified waiting time elapses.
257 * </ul>
258 *
259 * <p>If the count reaches zero then the method returns with the
260 * value {@code true}.
261 *
262 * <p>If the current thread:
263 * <ul>
264 * <li>has its interrupted status set on entry to this method; or
265 * <li>is {@linkplain Thread#interrupt interrupted} while waiting,
266 * </ul>
267 * then {@link InterruptedException} is thrown and the current thread's
268 * interrupted status is cleared.
269 *
270 * <p>If the specified waiting time elapses then the value {@code false}
271 * is returned. If the time is less than or equal to zero, the method
272 * will not wait at all.
273 *
274 * @param timeout the maximum time to wait
275 * @param unit the time unit of the {@code timeout} argument
276 * @return {@code true} if the count reached zero and {@code false}
277 * if the waiting time elapsed before the count reached zero
278 * @throws InterruptedException if the current thread is interrupted
279 * while waiting
280 */
281 public boolean await(long timeout, TimeUnit unit)
282 throws InterruptedException {
283 return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
284 }
285
286 /**
287 * Decrements the count of the latch, releasing all waiting threads if
288 * the count reaches zero.
289 *
290 * <p>If the current count is greater than zero then it is decremented.
291 * If the new count is zero then all waiting threads are re-enabled for
292 * thread scheduling purposes.
293 *
294 * <p>If the current count equals zero then nothing happens.
295 */
296 public void countDown() {
297 sync.releaseShared(1);
298 }
299
300 /**
301 * Returns the current count.
302 *
303 * <p>This method is typically used for debugging and testing purposes.
304 *
305 * @return the current count
306 */
307 public long getCount() {
308 return sync.getCount();
309 }
310
311 /**
312 * Returns a string identifying this latch, as well as its state.
313 * The state, in brackets, includes the String {@code "Count ="}
314 * followed by the current count.
315 *
316 * @return a string identifying this latch, as well as its state
317 */
318 public String toString() {
319 return super .toString() + "[Count = " + sync.getCount() + "]";
320 }
321 }
|