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