Класс Java.util.concurrent.Exchanger с примерами

Опубликовано: 7 Февраля, 2022

Exchanger - самый интересный класс синхронизации Java. Он облегчает обмен элементами между парой потоков за счет создания точки синхронизации . Это упрощает обмен данными между двумя потоками. Его работа проста: он просто ждет, пока два отдельных потока не вызовут его метод exchange (). Когда это происходит, он обменивается данными, предоставленными потоками. Его также можно рассматривать как двунаправленную SynchronousQueue . Это общий класс, который объявлен, как показано ниже.

Синтаксис класса:

 Обменник <V>

Здесь V указывает тип данных, которыми обмениваются.

Иерархия классов

java.lang.Object
↳ java.util.concurrent.Exchanger <V>

Конструктор:

  1. Exchanger () - создает новый объект Exchanger со значениями по умолчанию для его членов.

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:

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);
        }
    }
}
Output:
Got: ABCDE
Got: FGHIJ
Timeout Occurred

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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.