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