Multithreading: Exchanger hands two threads' data to each other

Exchanger.exchange() blocks until a second thread also calls exchange on the same instance, then each thread receives the value the other one offered. It is a rendezvous point built specifically for swapping exactly one object between exactly two threads.

Code
Exchanger<String> exchanger = new Exchanger<>();
String[] fromA = new String[1];
String[] fromB = new String[1];
Thread a = new Thread(() -> {
    try {
        fromA[0] = exchanger.exchange("A-data");
    } catch (InterruptedException e) { }
});
Thread b = new Thread(() -> {
    try {
        fromB[0] = exchanger.exchange("B-data");
    } catch (InterruptedException e) { }
});
a.start();
b.start();
a.join();
b.join();
System.out.println("Thread A received: " + fromA[0]);
System.out.println("Thread B received: " + fromB[0]);
Output
Thread A received: B-data
Thread B received: A-data
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms