2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
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.
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).
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.
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
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
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/publicdomain/zero/1.0/
36 package java.util.concurrent.locks;
37 import java.util.concurrent.*;
38 import java.util.Date;
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
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 "wait") 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}.
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.
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.
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>
80 * final Object[] items = new Object[100];
81 * int putptr, takeptr, count;
83 * public void put(Object x) throws InterruptedException {
86 * while (count == items.length)
87 * <b>notFull.await();</b>
89 * if (++putptr == items.length) putptr = 0;
91 * <b>notEmpty.signal();</b>
97 * public Object take() throws InterruptedException {
101 * <b>notEmpty.await();</b>
102 * Object x = items[takeptr];
103 * if (++takeptr == items.length) takeptr = 0;
105 * <b>notFull.signal();</b>
114 * (The {@link java.util.concurrent.ArrayBlockingQueue} class provides
115 * this functionality, so there is no reason to implement this
116 * sample usage class.)
118 * <p>A {@code Condition} implementation can provide behavior and semantics
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.
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.
137 * <p>Except where noted, passing a {@code null} value for any parameter
138 * will result in a {@link NullPointerException} being thrown.
140 * <h3>Implementation Considerations</h3>
142 * <p>When waiting upon a {@code Condition}, a "<em>spurious
143 * wakeup</em>" 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.
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.
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.
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
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.
179 public interface Condition {
182 * Causes the current thread to wait until it is signalled or
183 * {@linkplain Thread#interrupt interrupted}.
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:
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 "<em>spurious wakeup</em>" occurs.
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.
203 * <p>If the current thread:
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,
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
214 * <p><b>Implementation Considerations</b>
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.
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
228 * @throws InterruptedException if the current thread is interrupted
229 * (and interruption of thread suspension is supported)
231 void await() throws InterruptedException;
234 * Causes the current thread to wait until it is signalled.
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:
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 "<em>spurious wakeup</em>" occurs.
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.
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
258 * <p><b>Implementation Considerations</b>
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.
267 void awaitUninterruptibly();
270 * Causes the current thread to wait until it is signalled or interrupted,
271 * or the specified waiting time elapses.
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:
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 "<em>spurious wakeup</em>" occurs.
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.
292 * <p>If the current thread:
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,
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
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:
312 * boolean aMethod(long timeout, TimeUnit unit) {
313 * long nanos = unit.toNanos(timeout);
316 * while (!conditionBeingWaitedFor()) {
319 * nanos = theCondition.awaitNanos(nanos);
327 * <p> Design note: This method requires a nanosecond argument so
328 * as to avoid truncation errors in reporting remaining times.
329 * Such precision loss would make it difficult for programmers to
330 * ensure that total waiting times are not systematically shorter
331 * than specified when re-waits occur.
333 * <p><b>Implementation Considerations</b>
335 * <p>The current thread is assumed to hold the lock associated with this
336 * {@code Condition} when this method is called.
337 * It is up to the implementation to determine if this is
338 * the case and if not, how to respond. Typically, an exception will be
339 * thrown (such as {@link IllegalMonitorStateException}) and the
340 * implementation must document that fact.
342 * <p>An implementation can favor responding to an interrupt over normal
343 * method return in response to a signal, or over indicating the elapse
344 * of the specified waiting time. In either case the implementation
345 * must ensure that the signal is redirected to another waiting thread, if
348 * @param nanosTimeout the maximum time to wait, in nanoseconds
349 * @return an estimate of the {@code nanosTimeout} value minus
350 * the time spent waiting upon return from this method.
351 * A positive value may be used as the argument to a
352 * subsequent call to this method to finish waiting out
353 * the desired time. A value less than or equal to zero
354 * indicates that no time remains.
355 * @throws InterruptedException if the current thread is interrupted
356 * (and interruption of thread suspension is supported)
358 long awaitNanos(long nanosTimeout) throws InterruptedException;
361 * Causes the current thread to wait until it is signalled or interrupted,
362 * or the specified waiting time elapses. This method is behaviorally
365 * awaitNanos(unit.toNanos(time)) > 0
367 * @param time the maximum time to wait
368 * @param unit the time unit of the {@code time} argument
369 * @return {@code false} if the waiting time detectably elapsed
370 * before return from the method, else {@code true}
371 * @throws InterruptedException if the current thread is interrupted
372 * (and interruption of thread suspension is supported)
374 boolean await(long time, TimeUnit unit) throws InterruptedException;
377 * Causes the current thread to wait until it is signalled or interrupted,
378 * or the specified deadline elapses.
380 * <p>The lock associated with this condition is atomically
381 * released and the current thread becomes disabled for thread scheduling
382 * purposes and lies dormant until <em>one</em> of five things happens:
384 * <li>Some other thread invokes the {@link #signal} method for this
385 * {@code Condition} and the current thread happens to be chosen as the
386 * thread to be awakened; or
387 * <li>Some other thread invokes the {@link #signalAll} method for this
388 * {@code Condition}; or
389 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
390 * current thread, and interruption of thread suspension is supported; or
391 * <li>The specified deadline elapses; or
392 * <li>A "<em>spurious wakeup</em>" occurs.
395 * <p>In all cases, before this method can return the current thread must
396 * re-acquire the lock associated with this condition. When the
397 * thread returns it is <em>guaranteed</em> to hold this lock.
400 * <p>If the current thread:
402 * <li>has its interrupted status set on entry to this method; or
403 * <li>is {@linkplain Thread#interrupt interrupted} while waiting
404 * and interruption of thread suspension is supported,
406 * then {@link InterruptedException} is thrown and the current thread's
407 * interrupted status is cleared. It is not specified, in the first
408 * case, whether or not the test for interruption occurs before the lock
412 * <p>The return value indicates whether the deadline has elapsed,
413 * which can be used as follows:
415 * boolean aMethod(Date deadline) {
416 * boolean stillWaiting = true;
419 * while (!conditionBeingWaitedFor()) {
422 * stillWaiting = theCondition.awaitUntil(deadline);
430 * <p><b>Implementation Considerations</b>
432 * <p>The current thread is assumed to hold the lock associated with this
433 * {@code Condition} when this method is called.
434 * It is up to the implementation to determine if this is
435 * the case and if not, how to respond. Typically, an exception will be
436 * thrown (such as {@link IllegalMonitorStateException}) and the
437 * implementation must document that fact.
439 * <p>An implementation can favor responding to an interrupt over normal
440 * method return in response to a signal, or over indicating the passing
441 * of the specified deadline. In either case the implementation
442 * must ensure that the signal is redirected to another waiting thread, if
445 * @param deadline the absolute time to wait until
446 * @return {@code false} if the deadline has elapsed upon return, else
448 * @throws InterruptedException if the current thread is interrupted
449 * (and interruption of thread suspension is supported)
451 boolean awaitUntil(Date deadline) throws InterruptedException;
454 * Wakes up one waiting thread.
456 * <p>If any threads are waiting on this condition then one
457 * is selected for waking up. That thread must then re-acquire the
458 * lock before returning from {@code await}.
460 * <p><b>Implementation Considerations</b>
462 * <p>An implementation may (and typically does) require that the
463 * current thread hold the lock associated with this {@code
464 * Condition} when this method is called. Implementations must
465 * document this precondition and any actions taken if the lock is
466 * not held. Typically, an exception such as {@link
467 * IllegalMonitorStateException} will be thrown.
472 * Wakes up all waiting threads.
474 * <p>If any threads are waiting on this condition then they are
475 * all woken up. Each thread must re-acquire the lock before it can
476 * return from {@code await}.
478 * <p><b>Implementation Considerations</b>
480 * <p>An implementation may (and typically does) require that the
481 * current thread hold the lock associated with this {@code
482 * Condition} when this method is called. Implementations must
483 * document this precondition and any actions taken if the lock is
484 * not held. Typically, an exception such as {@link
485 * IllegalMonitorStateException} will be thrown.