Java.util.concurrent.Exchanger class with Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
  
public class ExchangerDemo {
    public static void main(String[] args)
    {
        Exchanger<String> exchanger = new Exchanger<>();
  
        new UseString(exchanger);
        new MakeString(exchanger);
    }
}
  
// A thread that makes a string
class MakeString implements Runnable {
    Exchanger<String> ex;
    String str;
  
    MakeString(Exchanger<String> ex)
    {
        this.ex = ex;
        str = new String();
  
        new Thread(this).start();
    }
  
    public void run()
    {
        char ch = 'A';
        try {
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 5; j++) {
                    str += ch++;
                }
                if (i == 2) {
                    // Exchange the buffer and
                    // only wait for 250 milliseconds
                    str
                        = ex.exchange(str,
                                      250,
                                      TimeUnit.MILLISECONDS);
                    continue;
                }
  
                // Exchange a full buffer for an empty one
                str = ex.exchange(str);
            }
        }
        catch (InterruptedException e) {
            System.out.println(e);
        }
        catch (TimeoutException t) {
            System.out.println("Timeout Occurred");
        }
    }
}
  
// A thread that uses a string
class UseString implements Runnable {
  
    Exchanger<String> ex;
    String str;
  
    UseString(Exchanger<String> ex)
    {
        this.ex = ex;
  
        new Thread(this).start();
    }
  
    public void run()
    {
        try {
            for (int i = 0; i < 3; i++) {
                if (i == 2) {
                    // Thread sleeps for 500 milliseconds
                    // causing timeout
                    Thread.sleep(500);
                    continue;
                }
  
                // Exchange an empty buffer for a full one
                str = ex.exchange(new String());
                System.out.println("Got: " + str);
            }
        }
        catch (InterruptedException e) {
            System.out.println(e);
        }
    }
}

chevron_right


Output:

Got: ABCDE
Got: FGHIJ
Timeout Occurred

Reference:https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Exchanger.html



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.