This documentation differs from the official API. Jadeite adds extra features to the API including: variable font sizes, constructions examples, placeholders for classes and methods, and auto-generated “See Also” links. Additionally it is missing some items found in standard Javadoc documentation, including: generics type information, “Deprecated” tags and comments, “See Also” links, along with other minor differences. Please send any questions or feedback to bam@cs.cmu.edu.


java.util.concurrent.locks
interface Condition

All Known Implementing Classes:
AbstractQueuedLongSynchronizer.ConditionObject, AbstractQueuedSynchronizer.ConditionObject

Most common way to construct:

ReentrantLock lock = …;

Condition c = lock.newCondition();

Based on 185 examples


public interface Condition

{@code Condition} factors out the {@code Object} monitor methods ({@link Object#wait() wait}, {@link Object#notify notify} and {@link Object#notifyAll notifyAll}) into distinct objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary {@link Lock} implementations. Where a {@code Lock} replaces the use of {@code synchronized} methods and statements, a {@code Condition} replaces the use of the Object monitor methods.

Conditions (also known as condition queues or condition variables) provide a means for one thread to suspend execution (to "wait") until notified by another thread that some state condition may now be true. Because access to this shared state information occurs in different threads, it must be protected, so a lock of some form is associated with the condition. The key property that waiting for a condition provides is that it atomically releases the associated lock and suspends the current thread, just like {@code Object.wait}.

A {@code Condition} instance is intrinsically bound to a lock. To obtain a {@code Condition} instance for a particular {@link Lock} instance use its {@link Lock#newCondition newCondition()} method.

As an example, suppose we have a bounded buffer which supports {@code put} and {@code take} methods. If a {@code take} is attempted on an empty buffer, then the thread will block until an item becomes available; if a {@code put} is attempted on a full buffer, then the thread will block until a space becomes available. We would like to keep waiting {@code put} threads and {@code take} threads in separate wait-sets so that we can use the optimization of only notifying a single thread at a time when items or spaces become available in the buffer. This can be achieved using two {@link Condition} instances.

 class BoundedBuffer {
   final Lock lock = new ReentrantLock();
   final Condition notFull  = lock.newCondition(); 
   final Condition notEmpty = lock.newCondition(); 

   final Object[] items = new Object[100];
   int putptr, takeptr, count;

   public void put(Object x) throws InterruptedException {
     lock.lock();
     try {
       while (count == items.length)
         notFull.await();
       items[putptr] = x;
       if (++putptr == items.length) putptr = 0;
       ++count;
       notEmpty.signal();
     } finally {
       lock.unlock();
     }
   }

   public Object take() throws InterruptedException {
     lock.lock();
     try {
       while (count == 0)
         notEmpty.await();
       Object x = items[takeptr];
       if (++takeptr == items.length) takeptr = 0;
       --count;
       notFull.signal();
       return x;
     } finally {
       lock.unlock();
     }
   }
 }
 
(The {@link java.util.concurrent.ArrayBlockingQueue} class provides this functionality, so there is no reason to implement this sample usage class.)

A {@code Condition} implementation can provide behavior and semantics that is different from that of the {@code Object} monitor methods, such as guaranteed ordering for notifications, or not requiring a lock to be held when performing notifications. If an implementation provides such specialized semantics then the implementation must document those semantics.

Note that {@code Condition} instances are just normal objects and can themselves be used as the target in a {@code synchronized} statement, and can have their own monitor {@link Object#wait wait} and {@link Object#notify notification} methods invoked. Acquiring the monitor lock of a {@code Condition} instance, or using its monitor methods, has no specified relationship with acquiring the {@link Lock} associated with that {@code Condition} or the use of its {@linkplain #await waiting} and {@linkplain #signal signalling} methods. It is recommended that to avoid confusion you never use {@code Condition} instances in this way, except perhaps within their own implementation.

Except where noted, passing a {@code null} value for any parameter will result in a {@link NullPointerException} being thrown.

Implementation Considerations

When waiting upon a {@code Condition}, a "spurious wakeup" is permitted to occur, in general, as a concession to the underlying platform semantics. This has little practical impact on most application programs as a {@code Condition} should always be waited upon in a loop, testing the state predicate that is being waited for. An implementation is free to remove the possibility of spurious wakeups but it is recommended that applications programmers always assume that they can occur and so always wait in a loop.

The three forms of condition waiting (interruptible, non-interruptible, and timed) may differ in their ease of implementation on some platforms and in their performance characteristics. In particular, it may be difficult to provide these features and maintain specific semantics such as ordering guarantees. Further, the ability to interrupt the actual suspension of the thread may not always be feasible to implement on all platforms.

Consequently, an implementation is not required to define exactly the same guarantees or semantics for all three forms of waiting, nor is it required to support interruption of the actual suspension of the thread.

An implementation is required to clearly document the semantics and guarantees provided by each of the waiting methods, and when an implementation does support interruption of thread suspension then it must obey the interruption semantics as defined in this interface.

As interruption generally implies cancellation, and checks for interruption are often infrequent, an implementation can favor responding to an interrupt over normal method return. This is true even if it can be shown that the interrupt occurred after another action may have unblocked the thread. An implementation should document this behavior.


Method Summary
 void

          Causes the current thread to wait until it is signalled or java.lang.Thread.interrupt.
 boolean
await(long time, TimeUnit unit)

          Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses.
 long
awaitNanos(long nanosTimeout)

          Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses.
 void

          Causes the current thread to wait until it is signalled.
 boolean
awaitUntil(Date deadline)

          Causes the current thread to wait until it is signalled or interrupted, or the specified deadline elapses.
 void

          Wakes up one waiting thread.
 void

          Wakes up all waiting threads.
 

Method Detail

await

public void await()
           throws InterruptedException
Causes the current thread to wait until it is signalled or {@linkplain Thread#interrupt interrupted}.

The lock associated with this {@code Condition} is atomically released and the current thread becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

In all cases, before this method can return the current thread must re-acquire the lock associated with this condition. When the thread returns it is guaranteed to hold this lock.

If the current thread:

then {@link InterruptedException} is thrown and the current thread's interrupted status is cleared. It is not specified, in the first case, whether or not the test for interruption occurs before the lock is released.

Implementation Considerations

The current thread is assumed to hold the lock associated with this {@code Condition} when this method is called. It is up to the implementation to determine if this is the case and if not, how to respond. Typically, an exception will be thrown (such as {@link IllegalMonitorStateException}) and the implementation must document that fact.

An implementation can favor responding to an interrupt over normal method return in response to a signal. In that case the implementation must ensure that the signal is redirected to another waiting thread, if there is one.

Throws:
InterruptedException - if the current thread is interrupted (and interruption of thread suspension is supported)

await

public boolean await(long time,
                     TimeUnit unit)
              throws InterruptedException
Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses. This method is behaviorally equivalent to:
   awaitNanos(unit.toNanos(time)) > 0
 

Parameters:
time - the maximum time to wait
unit - the time unit of the {@code time} argument
Returns:
{@code false} if the waiting time detectably elapsed before return from the method, else {@code true}
Throws:
InterruptedException - if the current thread is interrupted (and interruption of thread suspension is supported)

awaitNanos

public long awaitNanos(long nanosTimeout)
                throws InterruptedException
Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses.

The lock associated with this condition is atomically released and the current thread becomes disabled for thread scheduling purposes and lies dormant until one of five things happens:

In all cases, before this method can return the current thread must re-acquire the lock associated with this condition. When the thread returns it is guaranteed to hold this lock.

If the current thread:

then {@link InterruptedException} is thrown and the current thread's interrupted status is cleared. It is not specified, in the first case, whether or not the test for interruption occurs before the lock is released.

The method returns an estimate of the number of nanoseconds remaining to wait given the supplied {@code nanosTimeout} value upon return, or a value less than or equal to zero if it timed out. This value can be used to determine whether and how long to re-wait in cases where the wait returns but an awaited condition still does not hold. Typical uses of this method take the following form:

 synchronized boolean aMethod(long timeout, TimeUnit unit) {
   long nanosTimeout = unit.toNanos(timeout);
   while (!conditionBeingWaitedFor) {
     if (nanosTimeout > 0)
         nanosTimeout = theCondition.awaitNanos(nanosTimeout);
      else
        return false;
   }
   // ...
 }
 

Design note: This method requires a nanosecond argument so as to avoid truncation errors in reporting remaining times. Such precision loss would make it difficult for programmers to ensure that total waiting times are not systematically shorter than specified when re-waits occur.

Implementation Considerations

The current thread is assumed to hold the lock associated with this {@code Condition} when this method is called. It is up to the implementation to determine if this is the case and if not, how to respond. Typically, an exception will be thrown (such as {@link IllegalMonitorStateException}) and the implementation must document that fact.

An implementation can favor responding to an interrupt over normal method return in response to a signal, or over indicating the elapse of the specified waiting time. In either case the implementation must ensure that the signal is redirected to another waiting thread, if there is one.

Parameters:
nanosTimeout - the maximum time to wait, in nanoseconds
Returns:
an estimate of the {@code nanosTimeout} value minus the time spent waiting upon return from this method. A positive value may be used as the argument to a subsequent call to this method to finish waiting out the desired time. A value less than or equal to zero indicates that no time remains.
Throws:
InterruptedException - if the current thread is interrupted (and interruption of thread suspension is supported)

awaitUninterruptibly

public void awaitUninterruptibly()
Causes the current thread to wait until it is signalled.

The lock associated with this condition is atomically released and the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happens:

In all cases, before this method can return the current thread must re-acquire the lock associated with this condition. When the thread returns it is guaranteed to hold this lock.

If the current thread's interrupted status is set when it enters this method, or it is {@linkplain Thread#interrupt interrupted} while waiting, it will continue to wait until signalled. When it finally returns from this method its interrupted status will still be set.

Implementation Considerations

The current thread is assumed to hold the lock associated with this {@code Condition} when this method is called. It is up to the implementation to determine if this is the case and if not, how to respond. Typically, an exception will be thrown (such as {@link IllegalMonitorStateException}) and the implementation must document that fact.


awaitUntil

public boolean awaitUntil(Date deadline)
                   throws InterruptedException
Causes the current thread to wait until it is signalled or interrupted, or the specified deadline elapses.

The lock associated with this condition is atomically released and the current thread becomes disabled for thread scheduling purposes and lies dormant until one of five things happens:

In all cases, before this method can return the current thread must re-acquire the lock associated with this condition. When the thread returns it is guaranteed to hold this lock.

If the current thread:

then {@link InterruptedException} is thrown and the current thread's interrupted status is cleared. It is not specified, in the first case, whether or not the test for interruption occurs before the lock is released.

The return value indicates whether the deadline has elapsed, which can be used as follows:

 synchronized boolean aMethod(Date deadline) {
   boolean stillWaiting = true;
   while (!conditionBeingWaitedFor) {
     if (stillWaiting)
         stillWaiting = theCondition.awaitUntil(deadline);
      else
        return false;
   }
   // ...
 }
 

Implementation Considerations

The current thread is assumed to hold the lock associated with this {@code Condition} when this method is called. It is up to the implementation to determine if this is the case and if not, how to respond. Typically, an exception will be thrown (such as {@link IllegalMonitorStateException}) and the implementation must document that fact.

An implementation can favor responding to an interrupt over normal method return in response to a signal, or over indicating the passing of the specified deadline. In either case the implementation must ensure that the signal is redirected to another waiting thread, if there is one.

Parameters:
deadline - the absolute time to wait until
Returns:
{@code false} if the deadline has elapsed upon return, else {@code true}
Throws:
InterruptedException - if the current thread is interrupted (and interruption of thread suspension is supported)

signal

public void signal()
Wakes up one waiting thread.

If any threads are waiting on this condition then one is selected for waking up. That thread must then re-acquire the lock before returning from {@code await}.


signalAll

public void signalAll()
Wakes up all waiting threads.

If any threads are waiting on this condition then they are all woken up. Each thread must re-acquire the lock before it can return from {@code await}.



This documentation differs from the official API. Jadeite adds extra features to the API including: variable font sizes, constructions examples, placeholders for classes and methods, and auto-generated “See Also” links. Additionally it is missing some items found in standard Javadoc documentation, including: generics type information, “Deprecated” tags and comments, “See Also” links, along with other minor differences. Please send any questions or feedback to bam@cs.cmu.edu.
This page displays the Jadeite version of the documention, which is derived from the offical documentation that contains this copyright notice:
Copyright 2008 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.
The official Sun™ documentation can be found here at http://java.sun.com/javase/6/docs/api/.