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.locks; 37 38 import java.util.Date; 39 import 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<E> { 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(E 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 E take() throws InterruptedException { 99 * <b>lock.lock(); 100 * try {</b> 101 * while (count == 0) 102 * <b>notEmpty.await();</b> 103 * E x = (E) 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 * <h2>Implementation Considerations</h2> 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 */ 180 public 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 */ await()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 */ awaitUninterruptibly()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 * throws InterruptedException { 315 * long nanosRemaining = unit.toNanos(timeout); 316 * lock.lock(); 317 * try { 318 * while (!conditionBeingWaitedFor()) { 319 * if (nanosRemaining <= 0L) 320 * return false; 321 * nanosRemaining = theCondition.awaitNanos(nanosRemaining); 322 * } 323 * // ... 324 * return true; 325 * } finally { 326 * lock.unlock(); 327 * } 328 * }}</pre> 329 * 330 * <p>Design note: This method requires a nanosecond argument so 331 * as to avoid truncation errors in reporting remaining times. 332 * Such precision loss would make it difficult for programmers to 333 * ensure that total waiting times are not systematically shorter 334 * than specified when re-waits occur. 335 * 336 * <p><b>Implementation Considerations</b> 337 * 338 * <p>The current thread is assumed to hold the lock associated with this 339 * {@code Condition} when this method is called. 340 * It is up to the implementation to determine if this is 341 * the case and if not, how to respond. Typically, an exception will be 342 * thrown (such as {@link IllegalMonitorStateException}) and the 343 * implementation must document that fact. 344 * 345 * <p>An implementation can favor responding to an interrupt over normal 346 * method return in response to a signal, or over indicating the elapse 347 * of the specified waiting time. In either case the implementation 348 * must ensure that the signal is redirected to another waiting thread, if 349 * there is one. 350 * 351 * @param nanosTimeout the maximum time to wait, in nanoseconds 352 * @return an estimate of the {@code nanosTimeout} value minus 353 * the time spent waiting upon return from this method. 354 * A positive value may be used as the argument to a 355 * subsequent call to this method to finish waiting out 356 * the desired time. A value less than or equal to zero 357 * indicates that no time remains. 358 * @throws InterruptedException if the current thread is interrupted 359 * (and interruption of thread suspension is supported) 360 */ awaitNanos(long nanosTimeout)361 long awaitNanos(long nanosTimeout) throws InterruptedException; 362 363 /** 364 * Causes the current thread to wait until it is signalled or interrupted, 365 * or the specified waiting time elapses. This method is behaviorally 366 * equivalent to: 367 * <pre> {@code awaitNanos(unit.toNanos(time)) > 0}</pre> 368 * 369 * @param time the maximum time to wait 370 * @param unit the time unit of the {@code time} argument 371 * @return {@code false} if the waiting time detectably elapsed 372 * before return from the method, else {@code true} 373 * @throws InterruptedException if the current thread is interrupted 374 * (and interruption of thread suspension is supported) 375 */ await(long time, TimeUnit unit)376 boolean await(long time, TimeUnit unit) throws InterruptedException; 377 378 /** 379 * Causes the current thread to wait until it is signalled or interrupted, 380 * or the specified deadline elapses. 381 * 382 * <p>The lock associated with this condition is atomically 383 * released and the current thread becomes disabled for thread scheduling 384 * purposes and lies dormant until <em>one</em> of five things happens: 385 * <ul> 386 * <li>Some other thread invokes the {@link #signal} method for this 387 * {@code Condition} and the current thread happens to be chosen as the 388 * thread to be awakened; or 389 * <li>Some other thread invokes the {@link #signalAll} method for this 390 * {@code Condition}; or 391 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the 392 * current thread, and interruption of thread suspension is supported; or 393 * <li>The specified deadline elapses; or 394 * <li>A "<em>spurious wakeup</em>" occurs. 395 * </ul> 396 * 397 * <p>In all cases, before this method can return the current thread must 398 * re-acquire the lock associated with this condition. When the 399 * thread returns it is <em>guaranteed</em> to hold this lock. 400 * 401 * <p>If the current thread: 402 * <ul> 403 * <li>has its interrupted status set on entry to this method; or 404 * <li>is {@linkplain Thread#interrupt interrupted} while waiting 405 * and interruption of thread suspension is supported, 406 * </ul> 407 * then {@link InterruptedException} is thrown and the current thread's 408 * interrupted status is cleared. It is not specified, in the first 409 * case, whether or not the test for interruption occurs before the lock 410 * is released. 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 * throws InterruptedException { 417 * boolean stillWaiting = true; 418 * lock.lock(); 419 * try { 420 * while (!conditionBeingWaitedFor()) { 421 * if (!stillWaiting) 422 * return false; 423 * stillWaiting = theCondition.awaitUntil(deadline); 424 * } 425 * // ... 426 * return true; 427 * } finally { 428 * lock.unlock(); 429 * } 430 * }}</pre> 431 * 432 * <p><b>Implementation Considerations</b> 433 * 434 * <p>The current thread is assumed to hold the lock associated with this 435 * {@code Condition} when this method is called. 436 * It is up to the implementation to determine if this is 437 * the case and if not, how to respond. Typically, an exception will be 438 * thrown (such as {@link IllegalMonitorStateException}) and the 439 * implementation must document that fact. 440 * 441 * <p>An implementation can favor responding to an interrupt over normal 442 * method return in response to a signal, or over indicating the passing 443 * of the specified deadline. In either case the implementation 444 * must ensure that the signal is redirected to another waiting thread, if 445 * there is one. 446 * 447 * @param deadline the absolute time to wait until 448 * @return {@code false} if the deadline has elapsed upon return, else 449 * {@code true} 450 * @throws InterruptedException if the current thread is interrupted 451 * (and interruption of thread suspension is supported) 452 */ awaitUntil(Date deadline)453 boolean awaitUntil(Date deadline) throws InterruptedException; 454 455 /** 456 * Wakes up one waiting thread. 457 * 458 * <p>If any threads are waiting on this condition then one 459 * is selected for waking up. That thread must then re-acquire the 460 * lock before returning from {@code await}. 461 * 462 * <p><b>Implementation Considerations</b> 463 * 464 * <p>An implementation may (and typically does) require that the 465 * current thread hold the lock associated with this {@code 466 * Condition} when this method is called. Implementations must 467 * document this precondition and any actions taken if the lock is 468 * not held. Typically, an exception such as {@link 469 * IllegalMonitorStateException} will be thrown. 470 */ signal()471 void signal(); 472 473 /** 474 * Wakes up all waiting threads. 475 * 476 * <p>If any threads are waiting on this condition then they are 477 * all woken up. Each thread must re-acquire the lock before it can 478 * return from {@code await}. 479 * 480 * <p><b>Implementation Considerations</b> 481 * 482 * <p>An implementation may (and typically does) require that the 483 * current thread hold the lock associated with this {@code 484 * Condition} when this method is called. Implementations must 485 * document this precondition and any actions taken if the lock is 486 * not held. Typically, an exception such as {@link 487 * IllegalMonitorStateException} will be thrown. 488 */ signalAll()489 void signalAll(); 490 } 491