Exchanger

This Article is part of Series of Articles on Java 8 Concurrency Tutorial.
In this article, we’ll focus on a the concept of Exchanger in the Java language.

Exchanger

The exchanger class provides a kind of point for two threads, where threads can exchange their objects with other threads.An Exchanger may be viewed as a bidirectional form of a SynchronousQueue. Exchangers may be useful in applications such as genetic algorithms and pipeline designs.
When a thread arrives at an exchange point, it is necessary to wait for another thread to arrive. When other partners come in threads, two threads go forward to exchange threads.

In below example two threads are passing Integer values to each others. Both the Thread will wait until they receive the Information

Exchanger Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

class FirstThread implements Runnable {
private Exchanger<Integer> exchanger;

public FirstThread(Exchanger<Integer> exchanger) {
this.exchanger = exchanger;
}

@Override
public void run() {
try {
System.out.println("Passing information form FirstThread");
Integer exchange = exchanger.exchange(99);
System.out.println("Information Sent From FirstThread");
System.out.println("Received information from Second Thread." + exchange);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class SecondThread implements Runnable {
private Exchanger<Integer> exchanger;

public SecondThread(Exchanger<Integer> exchanger) {
this.exchanger = exchanger;
}

@Override
public void run() {

System.out.println("Receiving information from First Thread.");
try {

Integer exchange = exchanger.exchange(2);
System.out.println("Received information from first Thread." + exchange);
} catch (InterruptedException e) {
e.printStackTrace();
}

}

}
public class ExchangerExample {
public static void main(String[] args) {
Exchanger<Integer> exchanger = new Exchanger<>();

ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(2);
newFixedThreadPool.submit(new FirstThread(exchanger));
newFixedThreadPool.submit(new SecondThread(exchanger));
newFixedThreadPool.shutdown();
}
}
Share Comments