Source for java.util.concurrent.locks.Condition

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