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 36package java.util.concurrent.locks; 37 38import java.util.Date; 39import java.util.concurrent.TimeUnit; 40 41/** 42 * {@code Condition} factors out the {@code Object} monitor 43 * methods ({@link Object#wait() wait}, {@link Object#notify notify} 44 * and {@link Object#notifyAll notifyAll}) into distinct objects to 45 * give the effect of having multiple wait-sets per object, by 46 * combining them with the use of arbitrary {@link Lock} implementations. 47 * Where a {@code Lock} replaces the use of {@code synchronized} methods 48 * and statements, a {@code Condition} replaces the use of the Object 49 * monitor methods. 50 * 51 * <p>Conditions (also known as <em>condition queues</em> or 52 * <em>condition variables</em>) provide a means for one thread to 53 * suspend execution (to "wait") until notified by another 54 * thread that some state condition may now be true. Because access 55 * to this shared state information occurs in different threads, it 56 * must be protected, so a lock of some form is associated with the 57 * condition. The key property that waiting for a condition provides 58 * is that it <em>atomically</em> releases the associated lock and 59 * suspends the current thread, just like {@code Object.wait}. 60 * 61 * <p>A {@code Condition} instance is intrinsically bound to a lock. 62 * To obtain a {@code Condition} instance for a particular {@link Lock} 63 * instance use its {@link Lock#newCondition newCondition()} method. 64 * 65 * <p>As an example, suppose we have a bounded buffer which supports 66 * {@code put} and {@code take} methods. If a 67 * {@code take} is attempted on an empty buffer, then the thread will block 68 * until an item becomes available; if a {@code put} is attempted on a 69 * full buffer, then the thread will block until a space becomes available. 70 * We would like to keep waiting {@code put} threads and {@code take} 71 * threads in separate wait-sets so that we can use the optimization of 72 * only notifying a single thread at a time when items or spaces become 73 * available in the buffer. This can be achieved using two 74 * {@link Condition} instances. 75 * <pre> 76 * class BoundedBuffer { 77 * <b>final Lock lock = new ReentrantLock();</b> 78 * final Condition notFull = <b>lock.newCondition(); </b> 79 * final Condition notEmpty = <b>lock.newCondition(); </b> 80 * 81 * final Object[] items = new Object[100]; 82 * int putptr, takeptr, count; 83 * 84 * public void put(Object x) throws InterruptedException { 85 * <b>lock.lock(); 86 * try {</b> 87 * while (count == items.length) 88 * <b>notFull.await();</b> 89 * items[putptr] = x; 90 * if (++putptr == items.length) putptr = 0; 91 * ++count; 92 * <b>notEmpty.signal();</b> 93 * <b>} finally { 94 * lock.unlock(); 95 * }</b> 96 * } 97 * 98 * public Object take() throws InterruptedException { 99 * <b>lock.lock(); 100 * try {</b> 101 * while (count == 0) 102 * <b>notEmpty.await();</b> 103 * Object x = items[takeptr]; 104 * if (++takeptr == items.length) takeptr = 0; 105 * --count; 106 * <b>notFull.signal();</b> 107 * return x; 108 * <b>} finally { 109 * lock.unlock(); 110 * }</b> 111 * } 112 * } 113 * </pre> 114 * 115 * (The {@link java.util.concurrent.ArrayBlockingQueue} class provides 116 * this functionality, so there is no reason to implement this 117 * sample usage class.) 118 * 119 * <p>A {@code Condition} implementation can provide behavior and semantics 120 * that is 121 * different from that of the {@code Object} monitor methods, such as 122 * guaranteed ordering for notifications, or not requiring a lock to be held 123 * when performing notifications. 124 * If an implementation provides such specialized semantics then the 125 * implementation must document those semantics. 126 * 127 * <p>Note that {@code Condition} instances are just normal objects and can 128 * themselves be used as the target in a {@code synchronized} statement, 129 * and can have their own monitor {@link Object#wait wait} and 130 * {@link Object#notify notify} methods invoked. 131 * Acquiring the monitor lock of a {@code Condition} instance, or using its 132 * monitor methods, has no specified relationship with acquiring the 133 * {@link Lock} associated with that {@code Condition} or the use of its 134 * {@linkplain #await waiting} and {@linkplain #signal signalling} methods. 135 * It is recommended that to avoid confusion you never use {@code Condition} 136 * instances in this way, except perhaps within their own implementation. 137 * 138 * <p>Except where noted, passing a {@code null} value for any parameter 139 * will result in a {@link NullPointerException} being thrown. 140 * 141 * <h3>Implementation Considerations</h3> 142 * 143 * <p>When waiting upon a {@code Condition}, a "<em>spurious 144 * wakeup</em>" is permitted to occur, in 145 * general, as a concession to the underlying platform semantics. 146 * This has little practical impact on most application programs as a 147 * {@code Condition} should always be waited upon in a loop, testing 148 * the state predicate that is being waited for. An implementation is 149 * free to remove the possibility of spurious wakeups but it is 150 * recommended that applications programmers always assume that they can 151 * occur and so always wait in a loop. 152 * 153 * <p>The three forms of condition waiting 154 * (interruptible, non-interruptible, and timed) may differ in their ease of 155 * implementation on some platforms and in their performance characteristics. 156 * In particular, it may be difficult to provide these features and maintain 157 * specific semantics such as ordering guarantees. 158 * Further, the ability to interrupt the actual suspension of the thread may 159 * not always be feasible to implement on all platforms. 160 * 161 * <p>Consequently, an implementation is not required to define exactly the 162 * same guarantees or semantics for all three forms of waiting, nor is it 163 * required to support interruption of the actual suspension of the thread. 164 * 165 * <p>An implementation is required to 166 * clearly document the semantics and guarantees provided by each of the 167 * waiting methods, and when an implementation does support interruption of 168 * thread suspension then it must obey the interruption semantics as defined 169 * in this interface. 170 * 171 * <p>As interruption generally implies cancellation, and checks for 172 * interruption are often infrequent, an implementation can favor responding 173 * to an interrupt over normal method return. This is true even if it can be 174 * shown that the interrupt occurred after another action that may have 175 * unblocked the thread. An implementation should document this behavior. 176 * 177 * @since 1.5 178 * @author Doug Lea 179 */ 180public interface Condition { 181 182 /** 183 * Causes the current thread to wait until it is signalled or 184 * {@linkplain Thread#interrupt interrupted}. 185 * 186 * <p>The lock associated with this {@code Condition} is atomically 187 * released and the current thread becomes disabled for thread scheduling 188 * purposes and lies dormant until <em>one</em> of four things happens: 189 * <ul> 190 * <li>Some other thread invokes the {@link #signal} method for this 191 * {@code Condition} and the current thread happens to be chosen as the 192 * thread to be awakened; or 193 * <li>Some other thread invokes the {@link #signalAll} method for this 194 * {@code Condition}; or 195 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the 196 * current thread, and interruption of thread suspension is supported; or 197 * <li>A "<em>spurious wakeup</em>" occurs. 198 * </ul> 199 * 200 * <p>In all cases, before this method can return the current thread must 201 * re-acquire the lock associated with this condition. When the 202 * thread returns it is <em>guaranteed</em> to hold this lock. 203 * 204 * <p>If the current thread: 205 * <ul> 206 * <li>has its interrupted status set on entry to this method; or 207 * <li>is {@linkplain Thread#interrupt interrupted} while waiting 208 * and interruption of thread suspension is supported, 209 * </ul> 210 * then {@link InterruptedException} is thrown and the current thread's 211 * interrupted status is cleared. It is not specified, in the first 212 * case, whether or not the test for interruption occurs before the lock 213 * is released. 214 * 215 * <p><b>Implementation Considerations</b> 216 * 217 * <p>The current thread is assumed to hold the lock associated with this 218 * {@code Condition} when this method is called. 219 * It is up to the implementation to determine if this is 220 * the case and if not, how to respond. Typically, an exception will be 221 * thrown (such as {@link IllegalMonitorStateException}) and the 222 * implementation must document that fact. 223 * 224 * <p>An implementation can favor responding to an interrupt over normal 225 * method return in response to a signal. In that case the implementation 226 * must ensure that the signal is redirected to another waiting thread, if 227 * there is one. 228 * 229 * @throws InterruptedException if the current thread is interrupted 230 * (and interruption of thread suspension is supported) 231 */ 232 void await() throws InterruptedException; 233 234 /** 235 * Causes the current thread to wait until it is signalled. 236 * 237 * <p>The lock associated with this condition is atomically 238 * released and the current thread becomes disabled for thread scheduling 239 * purposes and lies dormant until <em>one</em> of three things happens: 240 * <ul> 241 * <li>Some other thread invokes the {@link #signal} method for this 242 * {@code Condition} and the current thread happens to be chosen as the 243 * thread to be awakened; or 244 * <li>Some other thread invokes the {@link #signalAll} method for this 245 * {@code Condition}; or 246 * <li>A "<em>spurious wakeup</em>" occurs. 247 * </ul> 248 * 249 * <p>In all cases, before this method can return the current thread must 250 * re-acquire the lock associated with this condition. When the 251 * thread returns it is <em>guaranteed</em> to hold this lock. 252 * 253 * <p>If the current thread's interrupted status is set when it enters 254 * this method, or it is {@linkplain Thread#interrupt interrupted} 255 * while waiting, it will continue to wait until signalled. When it finally 256 * returns from this method its interrupted status will still 257 * be set. 258 * 259 * <p><b>Implementation Considerations</b> 260 * 261 * <p>The current thread is assumed to hold the lock associated with this 262 * {@code Condition} when this method is called. 263 * It is up to the implementation to determine if this is 264 * the case and if not, how to respond. Typically, an exception will be 265 * thrown (such as {@link IllegalMonitorStateException}) and the 266 * implementation must document that fact. 267 */ 268 void awaitUninterruptibly(); 269 270 /** 271 * Causes the current thread to wait until it is signalled or interrupted, 272 * or the specified waiting time elapses. 273 * 274 * <p>The lock associated with this condition is atomically 275 * released and the current thread becomes disabled for thread scheduling 276 * purposes and lies dormant until <em>one</em> of five things happens: 277 * <ul> 278 * <li>Some other thread invokes the {@link #signal} method for this 279 * {@code Condition} and the current thread happens to be chosen as the 280 * thread to be awakened; or 281 * <li>Some other thread invokes the {@link #signalAll} method for this 282 * {@code Condition}; or 283 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the 284 * current thread, and interruption of thread suspension is supported; or 285 * <li>The specified waiting time elapses; or 286 * <li>A "<em>spurious wakeup</em>" occurs. 287 * </ul> 288 * 289 * <p>In all cases, before this method can return the current thread must 290 * re-acquire the lock associated with this condition. When the 291 * thread returns it is <em>guaranteed</em> to hold this lock. 292 * 293 * <p>If the current thread: 294 * <ul> 295 * <li>has its interrupted status set on entry to this method; or 296 * <li>is {@linkplain Thread#interrupt interrupted} while waiting 297 * and interruption of thread suspension is supported, 298 * </ul> 299 * then {@link InterruptedException} is thrown and the current thread's 300 * interrupted status is cleared. It is not specified, in the first 301 * case, whether or not the test for interruption occurs before the lock 302 * is released. 303 * 304 * <p>The method returns an estimate of the number of nanoseconds 305 * remaining to wait given the supplied {@code nanosTimeout} 306 * value upon return, or a value less than or equal to zero if it 307 * timed out. This value can be used to determine whether and how 308 * long to re-wait in cases where the wait returns but an awaited 309 * condition still does not hold. Typical uses of this method take 310 * the following form: 311 * 312 * <pre> {@code 313 * boolean aMethod(long timeout, TimeUnit unit) { 314 * long nanos = unit.toNanos(timeout); 315 * lock.lock(); 316 * try { 317 * while (!conditionBeingWaitedFor()) { 318 * if (nanos <= 0L) 319 * return false; 320 * nanos = theCondition.awaitNanos(nanos); 321 * } 322 * // ... 323 * } finally { 324 * lock.unlock(); 325 * } 326 * }}</pre> 327 * 328 * <p>Design note: This method requires a nanosecond argument so 329 * as to avoid truncation errors in reporting remaining times. 330 * Such precision loss would make it difficult for programmers to 331 * ensure that total waiting times are not systematically shorter 332 * than specified when re-waits occur. 333 * 334 * <p><b>Implementation Considerations</b> 335 * 336 * <p>The current thread is assumed to hold the lock associated with this 337 * {@code Condition} when this method is called. 338 * It is up to the implementation to determine if this is 339 * the case and if not, how to respond. Typically, an exception will be 340 * thrown (such as {@link IllegalMonitorStateException}) and the 341 * implementation must document that fact. 342 * 343 * <p>An implementation can favor responding to an interrupt over normal 344 * method return in response to a signal, or over indicating the elapse 345 * of the specified waiting time. In either case the implementation 346 * must ensure that the signal is redirected to another waiting thread, if 347 * there is one. 348 * 349 * @param nanosTimeout the maximum time to wait, in nanoseconds 350 * @return an estimate of the {@code nanosTimeout} value minus 351 * the time spent waiting upon return from this method. 352 * A positive value may be used as the argument to a 353 * subsequent call to this method to finish waiting out 354 * the desired time. A value less than or equal to zero 355 * indicates that no time remains. 356 * @throws InterruptedException if the current thread is interrupted 357 * (and interruption of thread suspension is supported) 358 */ 359 long awaitNanos(long nanosTimeout) throws InterruptedException; 360 361 /** 362 * Causes the current thread to wait until it is signalled or interrupted, 363 * or the specified waiting time elapses. This method is behaviorally 364 * equivalent to: 365 * <pre> {@code awaitNanos(unit.toNanos(time)) > 0}</pre> 366 * 367 * @param time the maximum time to wait 368 * @param unit the time unit of the {@code time} argument 369 * @return {@code false} if the waiting time detectably elapsed 370 * before return from the method, else {@code true} 371 * @throws InterruptedException if the current thread is interrupted 372 * (and interruption of thread suspension is supported) 373 */ 374 boolean await(long time, TimeUnit unit) throws InterruptedException; 375 376 /** 377 * Causes the current thread to wait until it is signalled or interrupted, 378 * or the specified deadline elapses. 379 * 380 * <p>The lock associated with this condition is atomically 381 * released and the current thread becomes disabled for thread scheduling 382 * purposes and lies dormant until <em>one</em> of five things happens: 383 * <ul> 384 * <li>Some other thread invokes the {@link #signal} method for this 385 * {@code Condition} and the current thread happens to be chosen as the 386 * thread to be awakened; or 387 * <li>Some other thread invokes the {@link #signalAll} method for this 388 * {@code Condition}; or 389 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the 390 * current thread, and interruption of thread suspension is supported; or 391 * <li>The specified deadline elapses; or 392 * <li>A "<em>spurious wakeup</em>" occurs. 393 * </ul> 394 * 395 * <p>In all cases, before this method can return the current thread must 396 * re-acquire the lock associated with this condition. When the 397 * thread returns it is <em>guaranteed</em> to hold this lock. 398 * 399 * 400 * <p>If the current thread: 401 * <ul> 402 * <li>has its interrupted status set on entry to this method; or 403 * <li>is {@linkplain Thread#interrupt interrupted} while waiting 404 * and interruption of thread suspension is supported, 405 * </ul> 406 * then {@link InterruptedException} is thrown and the current thread's 407 * interrupted status is cleared. It is not specified, in the first 408 * case, whether or not the test for interruption occurs before the lock 409 * is released. 410 * 411 * 412 * <p>The return value indicates whether the deadline has elapsed, 413 * which can be used as follows: 414 * <pre> {@code 415 * boolean aMethod(Date deadline) { 416 * boolean stillWaiting = true; 417 * lock.lock(); 418 * try { 419 * while (!conditionBeingWaitedFor()) { 420 * if (!stillWaiting) 421 * return false; 422 * stillWaiting = theCondition.awaitUntil(deadline); 423 * } 424 * // ... 425 * } finally { 426 * lock.unlock(); 427 * } 428 * }}</pre> 429 * 430 * <p><b>Implementation Considerations</b> 431 * 432 * <p>The current thread is assumed to hold the lock associated with this 433 * {@code Condition} when this method is called. 434 * It is up to the implementation to determine if this is 435 * the case and if not, how to respond. Typically, an exception will be 436 * thrown (such as {@link IllegalMonitorStateException}) and the 437 * implementation must document that fact. 438 * 439 * <p>An implementation can favor responding to an interrupt over normal 440 * method return in response to a signal, or over indicating the passing 441 * of the specified deadline. In either case the implementation 442 * must ensure that the signal is redirected to another waiting thread, if 443 * there is one. 444 * 445 * @param deadline the absolute time to wait until 446 * @return {@code false} if the deadline has elapsed upon return, else 447 * {@code true} 448 * @throws InterruptedException if the current thread is interrupted 449 * (and interruption of thread suspension is supported) 450 */ 451 boolean awaitUntil(Date deadline) throws InterruptedException; 452 453 /** 454 * Wakes up one waiting thread. 455 * 456 * <p>If any threads are waiting on this condition then one 457 * is selected for waking up. That thread must then re-acquire the 458 * lock before returning from {@code await}. 459 * 460 * <p><b>Implementation Considerations</b> 461 * 462 * <p>An implementation may (and typically does) require that the 463 * current thread hold the lock associated with this {@code 464 * Condition} when this method is called. Implementations must 465 * document this precondition and any actions taken if the lock is 466 * not held. Typically, an exception such as {@link 467 * IllegalMonitorStateException} will be thrown. 468 */ 469 void signal(); 470 471 /** 472 * Wakes up all waiting threads. 473 * 474 * <p>If any threads are waiting on this condition then they are 475 * all woken up. Each thread must re-acquire the lock before it can 476 * return from {@code await}. 477 * 478 * <p><b>Implementation Considerations</b> 479 * 480 * <p>An implementation may (and typically does) require that the 481 * current thread hold the lock associated with this {@code 482 * Condition} when this method is called. Implementations must 483 * document this precondition and any actions taken if the lock is 484 * not held. Typically, an exception such as {@link 485 * IllegalMonitorStateException} will be thrown. 486 */ 487 void signalAll(); 488} 489