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