Name

Exchanger<V>

Synopsis

This class allows two threads to rendezvous and exchange data. This is a generic type, and the type variable V represents the type of data to be exchanged. Each thread should call exchange( ) and pass the value of type V that it wants to exchange. The first thread to call exchange( ) blocks until the second thread calls it. At that point, both threads resume. Both threads receive as their return value the object of type V passed by the other thread. Note that this class also defines a timed version of exchange( ) that throws a TimeoutException if no exchange occurs within the specified timeout interval. Unlike a CountDownLatch, which is a one-shot latch, and CyclicBarrier which can be “broken,” an Exchanger may be reused for any number of exchanges.

public class Exchanger<V> {
// Public Constructors
     public Exchanger( );  
// Public Instance Methods
     public V exchange(V x) throws InterruptedException;  
     public V exchange(V x, long timeout, TimeUnit unit) 
        throws InterruptedException, TimeoutException;  
}

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.