1 /* 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 * 4 * This code is free software; you can redistribute it and/or modify it 5 * under the terms of the GNU General Public License version 2 only, as 6 * published by the Free Software Foundation. Oracle designates this 7 * particular file as subject to the "Classpath" exception as provided 8 * by Oracle in the LICENSE file that accompanied this code. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 */ 24 25 /* 26 * This file is available under and governed by the GNU General Public 27 * License version 2 only, as published by the Free Software Foundation. 28 * However, the following notice accompanied the original version of this 29 * file: 30 * 31 * Written by Doug Lea with assistance from members of JCP JSR-166 32 * Expert Group and released to the public domain, as explained at 33 * http://creativecommons.org/publicdomain/zero/1.0/ 34 */ 35 36 package java.util.concurrent; 37 38 import java.util.concurrent.locks.AbstractQueuedSynchronizer; 39 40 /** 41 * A synchronization aid that allows one or more threads to wait until 42 * a set of operations being performed in other threads completes. 43 * 44 * <p>A {@code CountDownLatch} is initialized with a given <em>count</em>. 45 * The {@link #await await} methods block until the current count reaches 46 * zero due to invocations of the {@link #countDown} method, after which 47 * all waiting threads are released and any subsequent invocations of 48 * {@link #await await} return immediately. This is a one-shot phenomenon 49 * -- the count cannot be reset. If you need a version that resets the 50 * count, consider using a {@link CyclicBarrier}. 51 * 52 * <p>A {@code CountDownLatch} is a versatile synchronization tool 53 * and can be used for a number of purposes. A 54 * {@code CountDownLatch} initialized with a count of one serves as a 55 * simple on/off latch, or gate: all threads invoking {@link #await await} 56 * wait at the gate until it is opened by a thread invoking {@link 57 * #countDown}. A {@code CountDownLatch} initialized to <em>N</em> 58 * can be used to make one thread wait until <em>N</em> threads have 59 * completed some action, or some action has been completed N times. 60 * 61 * <p>A useful property of a {@code CountDownLatch} is that it 62 * doesn't require that threads calling {@code countDown} wait for 63 * the count to reach zero before proceeding, it simply prevents any 64 * thread from proceeding past an {@link #await await} until all 65 * threads could pass. 66 * 67 * <p><b>Sample usage:</b> Here is a pair of classes in which a group 68 * of worker threads use two countdown latches: 69 * <ul> 70 * <li>The first is a start signal that prevents any worker from proceeding 71 * until the driver is ready for them to proceed; 72 * <li>The second is a completion signal that allows the driver to wait 73 * until all workers have completed. 74 * </ul> 75 * 76 * <pre> {@code 77 * class Driver { // ... 78 * void main() throws InterruptedException { 79 * CountDownLatch startSignal = new CountDownLatch(1); 80 * CountDownLatch doneSignal = new CountDownLatch(N); 81 * 82 * for (int i = 0; i < N; ++i) // create and start threads 83 * new Thread(new Worker(startSignal, doneSignal)).start(); 84 * 85 * doSomethingElse(); // don't let run yet 86 * startSignal.countDown(); // let all threads proceed 87 * doSomethingElse(); 88 * doneSignal.await(); // wait for all to finish 89 * } 90 * } 91 * 92 * class Worker implements Runnable { 93 * private final CountDownLatch startSignal; 94 * private final CountDownLatch doneSignal; 95 * Worker(CountDownLatch startSignal, CountDownLatch doneSignal) { 96 * this.startSignal = startSignal; 97 * this.doneSignal = doneSignal; 98 * } 99 * public void run() { 100 * try { 101 * startSignal.await(); 102 * doWork(); 103 * doneSignal.countDown(); 104 * } catch (InterruptedException ex) {} // return; 105 * } 106 * 107 * void doWork() { ... } 108 * }}</pre> 109 * 110 * <p>Another typical usage would be to divide a problem into N parts, 111 * describe each part with a Runnable that executes that portion and 112 * counts down on the latch, and queue all the Runnables to an 113 * Executor. When all sub-parts are complete, the coordinating thread 114 * will be able to pass through await. (When threads must repeatedly 115 * count down in this way, instead use a {@link CyclicBarrier}.) 116 * 117 * <pre> {@code 118 * class Driver2 { // ... 119 * void main() throws InterruptedException { 120 * CountDownLatch doneSignal = new CountDownLatch(N); 121 * Executor e = ...; 122 * 123 * for (int i = 0; i < N; ++i) // create and start threads 124 * e.execute(new WorkerRunnable(doneSignal, i)); 125 * 126 * doneSignal.await(); // wait for all to finish 127 * } 128 * } 129 * 130 * class WorkerRunnable implements Runnable { 131 * private final CountDownLatch doneSignal; 132 * private final int i; 133 * WorkerRunnable(CountDownLatch doneSignal, int i) { 134 * this.doneSignal = doneSignal; 135 * this.i = i; 136 * } 137 * public void run() { 138 * doWork(); 139 * doneSignal.countDown(); 140 * } 141 * 142 * void doWork() { ... } 143 * }}</pre> 144 * 145 * <p>Memory consistency effects: Until the count reaches 146 * zero, actions in a thread prior to calling 147 * {@code countDown()} 148 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> 149 * actions following a successful return from a corresponding 150 * {@code await()} in another thread. 151 * 152 * @since 1.5 153 * @author Doug Lea 154 */ 155 public class CountDownLatch { 156 /** 157 * Synchronization control For CountDownLatch. 158 * Uses AQS state to represent count. 159 */ 160 private static final class Sync extends AbstractQueuedSynchronizer { 161 private static final long serialVersionUID = 4982264981922014374L; 162 Sync(int count)163 Sync(int count) { 164 setState(count); 165 } 166 getCount()167 int getCount() { 168 return getState(); 169 } 170 tryAcquireShared(int acquires)171 protected int tryAcquireShared(int acquires) { 172 return (getState() == 0) ? 1 : -1; 173 } 174 tryReleaseShared(int releases)175 protected boolean tryReleaseShared(int releases) { 176 // Decrement count; signal when transition to zero 177 for (;;) { 178 int c = getState(); 179 if (c == 0) 180 return false; 181 int nextc = c - 1; 182 if (compareAndSetState(c, nextc)) 183 return nextc == 0; 184 } 185 } 186 } 187 188 private final Sync sync; 189 190 /** 191 * Constructs a {@code CountDownLatch} initialized with the given count. 192 * 193 * @param count the number of times {@link #countDown} must be invoked 194 * before threads can pass through {@link #await} 195 * @throws IllegalArgumentException if {@code count} is negative 196 */ CountDownLatch(int count)197 public CountDownLatch(int count) { 198 if (count < 0) throw new IllegalArgumentException("count < 0"); 199 this.sync = new Sync(count); 200 } 201 202 /** 203 * Causes the current thread to wait until the latch has counted down to 204 * zero, unless the thread is {@linkplain Thread#interrupt interrupted}. 205 * 206 * <p>If the current count is zero then this method returns immediately. 207 * 208 * <p>If the current count is greater than zero then the current 209 * thread becomes disabled for thread scheduling purposes and lies 210 * dormant until one of two 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 {@linkplain Thread#interrupt interrupts} 215 * the current thread. 216 * </ul> 217 * 218 * <p>If the current thread: 219 * <ul> 220 * <li>has its interrupted status set on entry to this method; or 221 * <li>is {@linkplain Thread#interrupt interrupted} while waiting, 222 * </ul> 223 * then {@link InterruptedException} is thrown and the current thread's 224 * interrupted status is cleared. 225 * 226 * @throws InterruptedException if the current thread is interrupted 227 * while waiting 228 */ await()229 public void await() throws InterruptedException { 230 sync.acquireSharedInterruptibly(1); 231 } 232 233 /** 234 * Causes the current thread to wait until the latch has counted down to 235 * zero, unless the thread is {@linkplain Thread#interrupt interrupted}, 236 * or the specified waiting time elapses. 237 * 238 * <p>If the current count is zero then this method returns immediately 239 * with the value {@code true}. 240 * 241 * <p>If the current count is greater than zero then the current 242 * thread becomes disabled for thread scheduling purposes and lies 243 * dormant until one of three things happen: 244 * <ul> 245 * <li>The count reaches zero due to invocations of the 246 * {@link #countDown} method; or 247 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 248 * the current thread; or 249 * <li>The specified waiting time elapses. 250 * </ul> 251 * 252 * <p>If the count reaches zero then the method returns with the 253 * value {@code true}. 254 * 255 * <p>If the current thread: 256 * <ul> 257 * <li>has its interrupted status set on entry to this method; or 258 * <li>is {@linkplain Thread#interrupt interrupted} while waiting, 259 * </ul> 260 * then {@link InterruptedException} is thrown and the current thread's 261 * interrupted status is cleared. 262 * 263 * <p>If the specified waiting time elapses then the value {@code false} 264 * is returned. If the time is less than or equal to zero, the method 265 * will not wait at all. 266 * 267 * @param timeout the maximum time to wait 268 * @param unit the time unit of the {@code timeout} argument 269 * @return {@code true} if the count reached zero and {@code false} 270 * if the waiting time elapsed before the count reached zero 271 * @throws InterruptedException if the current thread is interrupted 272 * while waiting 273 */ await(long timeout, TimeUnit unit)274 public boolean await(long timeout, TimeUnit unit) 275 throws InterruptedException { 276 return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); 277 } 278 279 /** 280 * Decrements the count of the latch, releasing all waiting threads if 281 * the count reaches zero. 282 * 283 * <p>If the current count is greater than zero then it is decremented. 284 * If the new count is zero then all waiting threads are re-enabled for 285 * thread scheduling purposes. 286 * 287 * <p>If the current count equals zero then nothing happens. 288 */ countDown()289 public void countDown() { 290 sync.releaseShared(1); 291 } 292 293 /** 294 * Returns the current count. 295 * 296 * <p>This method is typically used for debugging and testing purposes. 297 * 298 * @return the current count 299 */ getCount()300 public long getCount() { 301 return sync.getCount(); 302 } 303 304 /** 305 * Returns a string identifying this latch, as well as its state. 306 * The state, in brackets, includes the String {@code "Count ="} 307 * followed by the current count. 308 * 309 * @return a string identifying this latch, as well as its state 310 */ toString()311 public String toString() { 312 return super.toString() + "[Count = " + sync.getCount() + "]"; 313 } 314 } 315