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