KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > util > concurrent > locks > Condition


1 /*
2  * @(#)Condition.java 1.5 04/07/12
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN 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 JavaDoc;
11
12 /**
13  * <tt>Condition</tt> factors out the <tt>Object</tt> 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 <tt>Lock</tt> replaces the use of <tt>synchronized</tt> methods
19  * and statements, a <tt>Condition</tt> 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 <tt>Object.wait</tt>.
31  *
32  * <p>A <tt>Condition</tt> instance is intrinsically bound to a lock.
33  * To obtain a <tt>Condition</tt> 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  * <tt>put</tt> and <tt>take</tt> methods. If a
38  * <tt>take</tt> is attempted on an empty buffer, then the thread will block
39  * until an item becomes available; if a <tt>put</tt> is attempted on a
40  * full buffer, then the thread will block until a space becomes available.
41  * We would like to keep waiting <tt>put</tt> threads and <tt>take</tt>
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 <tt>Condition</tt> implementation can provide behavior and semantics
91  * that is
92  * different from that of the <tt>Object</tt> 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 <tt>Condition</tt> instances are just normal objects and can
99  * themselves be used as the target in a <tt>synchronized</tt> 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 <tt>Condition</tt> instance, or using its
103  * monitor methods, has no specified relationship with acquiring the
104  * {@link Lock} associated with that <tt>Condition</tt> or the use of its
105  * {@link #await waiting} and {@link #signal signalling} methods.
106  * It is recommended that to avoid confusion you never use <tt>Condition</tt>
107  * instances in this way, except perhaps within their own implementation.
108  *
109  * <p>Except where noted, passing a <tt>null</tt> 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 <tt>Condition</tt>, 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  * <tt>Condition</tt> 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  * <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  * <p>An implementation is required to
135  * clearly document the semantics and guarantees provided by each of the
136  * waiting methods, and when an implementation does support interruption of
137  * thread suspension then it must obey the interruption semantics as defined
138  * in this interface.
139  * <p>As interruption generally implies cancellation, and checks for
140  * interruption are often infrequent, an implementation can favor responding
141  * to an interrupt over normal method return. This is true even if it can be
142  * shown that the interrupt occurred after another action may have unblocked
143  * the thread. An implementation should document this behavior.
144  *
145  *
146  * @since 1.5
147  * @author Doug Lea
148  */

149 public interface Condition {
150
151     /**
152      * Causes the current thread to wait until it is signalled or
153      * {@link Thread#interrupt interrupted}.
154      *
155      * <p>The lock associated with this <tt>Condition</tt> is atomically
156      * released and the current thread becomes disabled for thread scheduling
157      * purposes and lies dormant until <em>one</em> of four things happens:
158      * <ul>
159      * <li>Some other thread invokes the {@link #signal} method for this
160      * <tt>Condition</tt> and the current thread happens to be chosen as the
161      * thread to be awakened; or
162      * <li>Some other thread invokes the {@link #signalAll} method for this
163      * <tt>Condition</tt>; or
164      * <li>Some other thread {@link Thread#interrupt interrupts} the current
165      * thread, and interruption of thread suspension is supported; or
166      * <li>A &quot;<em>spurious wakeup</em>&quot; occurs
167      * </ul>
168      *
169      * <p>In all cases, before this method can return the current thread must
170      * re-acquire the lock associated with this condition. When the
171      * thread returns it is <em>guaranteed</em> to hold this lock.
172      *
173      * <p>If the current thread:
174      * <ul>
175      * <li>has its interrupted status set on entry to this method; or
176      * <li>is {@link Thread#interrupt interrupted} while waiting
177      * and interruption of thread suspension is supported,
178      * </ul>
179      * then {@link InterruptedException} is thrown and the current thread's
180      * interrupted status is cleared. It is not specified, in the first
181      * case, whether or not the test for interruption occurs before the lock
182      * is released.
183      *
184      * <p><b>Implementation Considerations</b>
185      * <p>The current thread is assumed to hold the lock associated with this
186      * <tt>Condition</tt> when this method is called.
187      * It is up to the implementation to determine if this is
188      * the case and if not, how to respond. Typically, an exception will be
189      * thrown (such as {@link IllegalMonitorStateException}) and the
190      * implementation must document that fact.
191      *
192      * <p>An implementation can favor responding to an interrupt over normal
193      * method return in response to a signal. In that case the implementation
194      * must ensure that the signal is redirected to another waiting thread, if
195      * there is one.
196      *
197      * @throws InterruptedException if the current thread is interrupted (and
198      * interruption of thread suspension is supported).
199      **/

200     void await() throws InterruptedException JavaDoc;
201
202     /**
203      * Causes the current thread to wait until it is signalled.
204      *
205      * <p>The lock associated with this condition is atomically
206      * released and the current thread becomes disabled for thread scheduling
207      * purposes and lies dormant until <em>one</em> of three things happens:
208      * <ul>
209      * <li>Some other thread invokes the {@link #signal} method for this
210      * <tt>Condition</tt> and the current thread happens to be chosen as the
211      * thread to be awakened; or
212      * <li>Some other thread invokes the {@link #signalAll} method for this
213      * <tt>Condition</tt>; or
214      * <li>A &quot;<em>spurious wakeup</em>&quot; occurs
215      * </ul>
216      *
217      * <p>In all cases, before this method can return the current thread must
218      * re-acquire the lock associated with this condition. When the
219      * thread returns it is <em>guaranteed</em> to hold this lock.
220      *
221      * <p>If the current thread's interrupted status is set when it enters
222      * this method, or it is {@link Thread#interrupt interrupted}
223      * while waiting, it will continue to wait until signalled. When it finally
224      * returns from this method its interrupted status will still
225      * be set.
226      *
227      * <p><b>Implementation Considerations</b>
228      * <p>The current thread is assumed to hold the lock associated with this
229      * <tt>Condition</tt> when this method is called.
230      * It is up to the implementation to determine if this is
231      * the case and if not, how to respond. Typically, an exception will be
232      * thrown (such as {@link IllegalMonitorStateException}) and the
233      * implementation must document that fact.
234      *
235      **/

236     void awaitUninterruptibly();
237
238     /**
239      * Causes the current thread to wait until it is signalled or interrupted,
240      * or the specified waiting time elapses.
241      *
242      * <p>The lock associated with this condition is atomically
243      * released and the current thread becomes disabled for thread scheduling
244      * purposes and lies dormant until <em>one</em> of five things happens:
245      * <ul>
246      * <li>Some other thread invokes the {@link #signal} method for this
247      * <tt>Condition</tt> and the current thread happens to be chosen as the
248      * thread to be awakened; or
249      * <li>Some other thread invokes the {@link #signalAll} method for this
250      * <tt>Condition</tt>; or
251      * <li>Some other thread {@link Thread#interrupt interrupts} the current
252      * thread, and interruption of thread suspension is supported; or
253      * <li>The specified waiting time elapses; or
254      * <li>A &quot;<em>spurious wakeup</em>&quot; occurs.
255      * </ul>
256      *
257      * <p>In all cases, before this method can return the current thread must
258      * re-acquire the lock associated with this condition. When the
259      * thread returns it is <em>guaranteed</em> to hold this lock.
260      *
261      * <p>If the current thread:
262      * <ul>
263      * <li>has its interrupted status set on entry to this method; or
264      * <li>is {@link Thread#interrupt interrupted} while waiting
265      * and interruption of thread suspension is supported,
266      * </ul>
267      * then {@link InterruptedException} is thrown and the current thread's
268      * interrupted status is cleared. It is not specified, in the first
269      * case, whether or not the test for interruption occurs before the lock
270      * is released.
271      *
272      * <p>The method returns an estimate of the number of nanoseconds
273      * remaining to wait given the supplied <tt>nanosTimeout</tt>
274      * value upon return, or a value less than or equal to zero if it
275      * timed out. This value can be used to determine whether and how
276      * long to re-wait in cases where the wait returns but an awaited
277      * condition still does not hold. Typical uses of this method take
278      * the following form:
279      *
280      * <pre>
281      * synchronized boolean aMethod(long timeout, TimeUnit unit) {
282      * long nanosTimeout = unit.toNanos(timeout);
283      * while (!conditionBeingWaitedFor) {
284      * if (nanosTimeout &gt; 0)
285      * nanosTimeout = theCondition.awaitNanos(nanosTimeout);
286      * else
287      * return false;
288      * }
289      * // ...
290      * }
291      * </pre>
292      *
293      * <p> Design note: This method requires a nanosecond argument so
294      * as to avoid truncation errors in reporting remaining times.
295      * Such precision loss would make it difficult for programmers to
296      * ensure that total waiting times are not systematically shorter
297      * than specified when re-waits occur.
298      *
299      * <p><b>Implementation Considerations</b>
300      * <p>The current thread is assumed to hold the lock associated with this
301      * <tt>Condition</tt> when this method is called.
302      * It is up to the implementation to determine if this is
303      * the case and if not, how to respond. Typically, an exception will be
304      * thrown (such as {@link IllegalMonitorStateException}) and the
305      * implementation must document that fact.
306      *
307      * <p>An implementation can favor responding to an interrupt over normal
308      * method return in response to a signal, or over indicating the elapse
309      * of the specified waiting time. In either case the implementation
310      * must ensure that the signal is redirected to another waiting thread, if
311      * there is one.
312      *
313      * @param nanosTimeout the maximum time to wait, in nanoseconds
314      * @return A value less than or equal to zero if the wait has
315      * timed out; otherwise an estimate, that
316      * is strictly less than the <tt>nanosTimeout</tt> argument,
317      * of the time still remaining when this method returned.
318      *
319      * @throws InterruptedException if the current thread is interrupted (and
320      * interruption of thread suspension is supported).
321      */

322     long awaitNanos(long nanosTimeout) throws InterruptedException JavaDoc;
323
324     /**
325      * Causes the current thread to wait until it is signalled or interrupted,
326      * or the specified waiting time elapses. This method is behaviorally
327      * equivalent to:<br>
328      * <pre>
329      * awaitNanos(unit.toNanos(time)) &gt; 0
330      * </pre>
331      * @param time the maximum time to wait
332      * @param unit the time unit of the <tt>time</tt> argument.
333      * @return <tt>false</tt> if the waiting time detectably elapsed
334      * before return from the method, else <tt>true</tt>.
335      * @throws InterruptedException if the current thread is interrupted (and
336      * interruption of thread suspension is supported).
337      */

338     boolean await(long time, TimeUnit unit) throws InterruptedException JavaDoc;
339     
340     /**
341      * Causes the current thread to wait until it is signalled or interrupted,
342      * or the specified deadline elapses.
343      *
344      * <p>The lock associated with this condition is atomically
345      * released and the current thread becomes disabled for thread scheduling
346      * purposes and lies dormant until <em>one</em> of five things happens:
347      * <ul>
348      * <li>Some other thread invokes the {@link #signal} method for this
349      * <tt>Condition</tt> and the current thread happens to be chosen as the
350      * thread to be awakened; or
351      * <li>Some other thread invokes the {@link #signalAll} method for this
352      * <tt>Condition</tt>; or
353      * <li>Some other thread {@link Thread#interrupt interrupts} the current
354      * thread, and interruption of thread suspension is supported; or
355      * <li>The specified deadline elapses; or
356      * <li>A &quot;<em>spurious wakeup</em>&quot; occurs.
357      * </ul>
358      *
359      * <p>In all cases, before this method can return the current thread must
360      * re-acquire the lock associated with this condition. When the
361      * thread returns it is <em>guaranteed</em> to hold this lock.
362      *
363      *
364      * <p>If the current thread:
365      * <ul>
366      * <li>has its interrupted status set on entry to this method; or
367      * <li>is {@link Thread#interrupt interrupted} while waiting
368      * and interruption of thread suspension is supported,
369      * </ul>
370      * then {@link InterruptedException} is thrown and the current thread's
371      * interrupted status is cleared. It is not specified, in the first
372      * case, whether or not the test for interruption occurs before the lock
373      * is released.
374      *
375      *
376      * <p>The return value indicates whether the deadline has elapsed,
377      * which can be used as follows:
378      * <pre>
379      * synchronized boolean aMethod(Date deadline) {
380      * boolean stillWaiting = true;
381      * while (!conditionBeingWaitedFor) {
382      * if (stillwaiting)
383      * stillWaiting = theCondition.awaitUntil(deadline);
384      * else
385      * return false;
386      * }
387      * // ...
388      * }
389      * </pre>
390      *
391      * <p><b>Implementation Considerations</b>
392      * <p>The current thread is assumed to hold the lock associated with this
393      * <tt>Condition</tt> when this method is called.
394      * It is up to the implementation to determine if this is
395      * the case and if not, how to respond. Typically, an exception will be
396      * thrown (such as {@link IllegalMonitorStateException}) and the
397      * implementation must document that fact.
398      *
399      * <p>An implementation can favor responding to an interrupt over normal
400      * method return in response to a signal, or over indicating the passing
401      * of the specified deadline. In either case the implementation
402      * must ensure that the signal is redirected to another waiting thread, if
403      * there is one.
404      *
405      *
406      * @param deadline the absolute time to wait until
407      * @return <tt>false</tt> if the deadline has
408      * elapsed upon return, else <tt>true</tt>.
409      *
410      * @throws InterruptedException if the current thread is interrupted (and
411      * interruption of thread suspension is supported).
412      */

413     boolean awaitUntil(Date JavaDoc deadline) throws InterruptedException JavaDoc;
414
415     /**
416      * Wakes up one waiting thread.
417      *
418      * <p>If any threads are waiting on this condition then one
419      * is selected for waking up. That thread must then re-acquire the
420      * lock before returning from <tt>await</tt>.
421      **/

422     void signal();
423
424     /**
425      * Wakes up all waiting threads.
426      *
427      * <p>If any threads are waiting on this condition then they are
428      * all woken up. Each thread must re-acquire the lock before it can
429      * return from <tt>await</tt>.
430      **/

431     void signalAll();
432
433 }
434
435
436
437
438
439
440
441
Popular Tags