Exchanger Swap Between Two Threads

Meet another thread at an Exchanger and trade objects in one atomic handoff — exchange() blocks until both sides arrive, then returns the partner object.

JavaResilience

Code

snippet
import java.util.concurrent.Exchanger;

public class BufferSwap {

    public static void main(String[] args) throws InterruptedException {
        Exchanger<String> exchanger = new Exchanger<>();
        // swap:双方各自带一个对象到达,exchange() 返回的是对方的对象
        Thread filler = new Thread(() -> {
            try {
                String received = exchanger.exchange("full-buffer");
                System.out.println("filler received: " + received);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        Thread drainer = new Thread(() -> {
            try {
                String received = exchanger.exchange("empty-buffer");
                System.out.println("drainer received: " + received);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        filler.start();
        drainer.start();
        filler.join();
        drainer.join();
    }
}

What the code does

Count the class BufferSwap as the entire surface area of Exchanger Swap Between Two Threads.

Applying it

Output lines are prefixed (filler received:, drainer received:), making each step’s effect easy to spot.

Statements that matter

Thread.currentThread().interrupt();

Interactive Tools for This Topic

FAQ

What does Exchanger Swap Between Two Threads print when run?
Running the file directly is enough — expect labeled output lines such as `filler received:`, `drainer received:`.