Open In App

Java.util.concurrent.Exchanger class with Examples

Last Updated : 30 May, 2019
Comments
Improve
Suggest changes
1 Like
Like
Report
Exchanger is the most interesting synchronization class of Java. It facilitates the exchange of elements between a pair of threads by creating a synchronization point. It simplifies the exchange of data between two threads. Its operation is simple: it simply waits until two separate threads call its exchange() method. When that occurs, it exchanges the data supplied by the threads. It can also be viewed as a bidirectional SynchronousQueue. It is a generic class that is declared as below. Class Syntax:
Exchanger<V>
Here, V specifies the type of data being exchanged. Class Hierarchy
java.lang.Object
↳ java.util.concurrent.Exchanger<V>
Constructor:
  1. Exchanger() - Creates a new Exchanger object with default values for its members.
Methods:
  1. exchange(V x)- When invoked this function causes the current thread to suspend its execution and wait for another thread to call its exchange method. When another thread calls its exchange method, the threads exchange their data and the execution resumes. Syntax:
    public V exchange(V x)
    throws InterruptedException
    
  2. exchange(V x, long timeout, TimeUnit unit)- When invoked this function causes the current thread to suspend its execution and wait for another thread to call its exchange method. When another thread calls its exchange method, the threads exchange their data and the execution resumes. The thread waits only for the duration specified by the timeout argument and in case if timeout duration elapses, a TimeoutException is thrown. Syntax:
    public V exchange(V x, long timeout, TimeUnit unit)
    throws InterruptedException, TimeoutException
    
Example to demonstrate working of Exchanger class:
Output:
Got: ABCDE
Got: FGHIJ
Timeout Occurred
Reference:https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Exchanger.html

Next Article
Practice Tags :

Similar Reads