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/publicdomain/zero/1.0/
5 */
6
7package java.util.concurrent.locks;
8
9import java.util.Date;
10import java.util.concurrent.TimeUnit;
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 notify} 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 that may have
146 * unblocked the thread. An implementation should document this behavior.
147 *
148 * @since 1.5
149 * @author Doug Lea
150 */
151public 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> {@code
284     * boolean aMethod(long timeout, TimeUnit unit) {
285     *   long nanos = unit.toNanos(timeout);
286     *   lock.lock();
287     *   try {
288     *     while (!conditionBeingWaitedFor()) {
289     *       if (nanos <= 0L)
290     *         return false;
291     *       nanos = theCondition.awaitNanos(nanos);
292     *     }
293     *     // ...
294     *   } finally {
295     *     lock.unlock();
296     *   }
297     * }}</pre>
298     *
299     * <p>Design note: This method requires a nanosecond argument so
300     * as to avoid truncation errors in reporting remaining times.
301     * Such precision loss would make it difficult for programmers to
302     * ensure that total waiting times are not systematically shorter
303     * than specified when re-waits occur.
304     *
305     * <p><b>Implementation Considerations</b>
306     *
307     * <p>The current thread is assumed to hold the lock associated with this
308     * {@code Condition} when this method is called.
309     * It is up to the implementation to determine if this is
310     * the case and if not, how to respond. Typically, an exception will be
311     * thrown (such as {@link IllegalMonitorStateException}) and the
312     * implementation must document that fact.
313     *
314     * <p>An implementation can favor responding to an interrupt over normal
315     * method return in response to a signal, or over indicating the elapse
316     * of the specified waiting time. In either case the implementation
317     * must ensure that the signal is redirected to another waiting thread, if
318     * there is one.
319     *
320     * @param nanosTimeout the maximum time to wait, in nanoseconds
321     * @return an estimate of the {@code nanosTimeout} value minus
322     *         the time spent waiting upon return from this method.
323     *         A positive value may be used as the argument to a
324     *         subsequent call to this method to finish waiting out
325     *         the desired time.  A value less than or equal to zero
326     *         indicates that no time remains.
327     * @throws InterruptedException if the current thread is interrupted
328     *         (and interruption of thread suspension is supported)
329     */
330    long awaitNanos(long nanosTimeout) throws InterruptedException;
331
332    /**
333     * Causes the current thread to wait until it is signalled or interrupted,
334     * or the specified waiting time elapses. This method is behaviorally
335     * equivalent to:
336     * <pre> {@code awaitNanos(unit.toNanos(time)) > 0}</pre>
337     *
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