Exchanger

An Exchanger is a meeting point for exactly two threads. Each brings an object, waits for the other to arrive, and leaves with the other's object. It is a niche tool, but for one pattern, two threads passing buffers back and forth, it fits exactly. This page explains how it works, runs a swap and the double-buffer pattern, shows what goes wrong with more than two threads, and measures it against queues.

Contents

How an Exchanger works

java.util.concurrent.Exchanger<V> (Java 5) has essentially one method, exchange(V x). The first thread to call it waits. When a second thread calls it, the two objects swap places: each call returns the object the other thread passed in, and both threads continue. It is a two-way version of SynchronousQueue, where data flows in both directions at once.

Inside, an exchanger has a single slot. The first thread puts its item in the slot and spins briefly, then parks. The second thread takes the item, leaves its own, and wakes the first. When many threads use the same exchanger, it switches to an array of slots, an "arena", so that pairs can meet in different slots without fighting over one memory location. Either way, pairing is first come, first served: the exchanger does not know or care which threads meet.

The swap also transfers visibility. The Javadoc states that, for each pair of threads that exchange, actions before exchange() in each thread happen-before those after the return from the matching exchange() in the other. A thread can fill a plain ArrayList, exchange it, and the other thread is guaranteed to see every element without any extra synchronization.

Exchanger and the other hand-off tools
ToolSinceDirectionThreadsBest for
ExchangerJava 5Both ways, at the same momentTwo at a timeSwapping buffers between a fixed pair
SynchronousQueueJava 5One way, producer waits for consumerAny numberDirect hand-off of single items
ArrayBlockingQueueJava 5One way, bufferedAny numberProducer-consumer with a bound
Two queuesJava 5Both ways, bufferedAny numberBuffer recycling with more than two threads
CompletableFutureJava 8One way, one valueAny numberDelivering a single result

Real uses are few but clear. The classic one is double buffering between two pipeline stages, such as a thread that reads blocks from a file and a thread that compresses them. Others are two threads that swap partial results at checkpoints, and simulations or genetic algorithms where pairs of workers trade data. In each case the two partners are fixed and the objects being swapped are large, so the cost of meeting is paid rarely.

These programs ran on JDK 21. Where timing matters, the programs print rounded values or checks, so the output is the same on every run.

A basic swap

Alice and Bob each bring an item. Bob arrives 200 ms late, so Alice must wait. Each thread stores what it received, and main prints the results after both have finished, because the order in which two threads print is not fixed.

Java
import java.util.concurrent.Exchanger;

public class BasicExchange {

    record Item(String what, String owner) { }

    public static void main(String[] args) throws InterruptedException {
        Exchanger<Item> exchanger = new Exchanger<>();
        Item apple = new Item("apple", "alice");
        Item book = new Item("book", "bob");
        Item[] received = new Item[2];

        Thread alice = new Thread(() -> {
            try {
                received[0] = exchanger.exchange(apple);   // arrives first and waits
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        Thread bob = new Thread(() -> {
            try {
                Thread.sleep(200);                         // bob is 200 ms late
                received[1] = exchanger.exchange(book);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        long start = System.nanoTime();
        alice.start();
        bob.start();
        alice.join();
        bob.join();
        long ms = (System.nanoTime() - start) / 1000000;

        System.out.println("alice received: " + received[0]);
        System.out.println("bob received:   " + received[1]);
        System.out.println("same object, not a copy: " + (received[0] == book));
        System.out.println("swap completed after ~" + (ms / 100) * 100 + " ms");
    }
}

Output:

Output
alice received: Item[what=book, owner=bob]
bob received:   Item[what=apple, owner=alice]
same object, not a copy: true
swap completed after ~200 ms
  • Alice received Bob's book and Bob received Alice's apple. The swap completed after about 200 ms, the moment Bob arrived; Alice spent that time blocked inside exchange.
  • "same object, not a copy" is true: the exchanger passes references. If both threads keep using an object after giving it away, they share it again, so treat an exchanged object as handed over.
  • Reading the received array in main is safe because of join(), not because of the exchanger: main took no part in the exchange.

Double buffering: the pattern Exchanger is made for

A producer fills a buffer while a consumer drains another one. When the producer's buffer is full and the consumer's is empty, they swap. Only two buffers ever exist, so a long-running pipeline allocates nothing per batch. The program moves 5 batches of 1,000 numbers and checks the sum, 1 + 2 + ... + 5,000 = 12,502,500.

Java
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Exchanger;

public class DoubleBuffer {

    static final int BATCHES = 5;
    static final int BATCH_SIZE = 1000;

    public static void main(String[] args) throws InterruptedException {
        Exchanger<List<Integer>> exchanger = new Exchanger<>();
        Map<List<Integer>, Boolean> buffersSeen = new IdentityHashMap<>();
        long[] consumed = new long[1];

        // The producer fills a buffer, then swaps it for the consumer's empty one
        Thread producer = new Thread(() -> {
            List<Integer> buffer = new ArrayList<>(BATCH_SIZE);
            int next = 1;
            try {
                for (int b = 0; b < BATCHES; b++) {
                    while (buffer.size() < BATCH_SIZE) {
                        buffer.add(next++);
                    }
                    buffer = exchanger.exchange(buffer);   // gets back an empty buffer
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // The consumer swaps its empty buffer for a full one, then drains it
        Thread consumer = new Thread(() -> {
            List<Integer> buffer = new ArrayList<>(BATCH_SIZE);
            try {
                for (int b = 0; b < BATCHES; b++) {
                    buffer = exchanger.exchange(buffer);   // gets back a full buffer
                    buffersSeen.put(buffer, true);
                    System.out.println("batch " + (b + 1) + ": " + buffer.size() + " items, "
                            + buffer.get(0) + " .. " + buffer.get(buffer.size() - 1));
                    for (int v : buffer) {
                        consumed[0] += v;
                    }
                    buffer.clear();                         // reuse it, do not allocate
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
        producer.join();
        consumer.join();
        long n = (long) BATCHES * BATCH_SIZE;
        System.out.println("sum consumed " + consumed[0] + ", expected " + n * (n + 1) / 2);
        System.out.println("distinct full buffers the consumer received: " + buffersSeen.size());
    }
}

Output:

Output
batch 1: 1000 items, 1 .. 1000
batch 2: 1000 items, 1001 .. 2000
batch 3: 1000 items, 2001 .. 3000
batch 4: 1000 items, 3001 .. 4000
batch 5: 1000 items, 4001 .. 5000
sum consumed 12502500, expected 12502500
distinct full buffers the consumer received: 2
  • Every batch arrived complete and in order, and the sum is exactly 12,502,500. The consumer read a plain ArrayList filled by another thread; the exchanger's happens-before guarantee made that safe.
  • The consumer received only 2 distinct buffer objects over 5 batches, counted with an IdentityHashMap so that two lists with equal contents still count as different objects. The two lists were passed back and forth and cleared, never replaced.
  • The exchange is also flow control. If the producer is faster, it waits at exchange until the consumer has finished the previous batch, so at most one batch is ever waiting. A queue would need a bound to achieve the same.
  • Exchanging is the only point where the threads touch each other's data. Between exchanges each thread owns its buffer completely, so no lock is needed while filling or draining it.

More than two threads: random pairs

The Javadoc describes an exchanger as a synchronization point at which threads can pair. With more than two threads, any two that arrive together pair up. The program releases 4 and then 3 threads at once onto one exchanger, each offering its own name with a 500 ms timeout, and checks the outcome rather than printing who met whom, because that changes between runs.

Java
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class MoreThanTwo {

    public static void main(String[] args) throws InterruptedException {
        for (int threads : new int[] {4, 3}) {
            run(threads);
        }
    }

    // Several threads share one Exchanger: they pair up, but who meets whom is not controlled
    static void run(int threads) throws InterruptedException {
        Exchanger<String> exchanger = new Exchanger<>();
        Map<String, String> got = new ConcurrentHashMap<>();
        CountDownLatch go = new CountDownLatch(1);
        Thread[] ts = new Thread[threads];
        for (int i = 0; i < threads; i++) {
            String me = "t" + i;
            ts[i] = new Thread(() -> {
                try {
                    go.await();
                    got.put(me, exchanger.exchange(me, 500, TimeUnit.MILLISECONDS));
                } catch (TimeoutException e) {
                    got.put(me, "TIMEOUT");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
            ts[i].start();
        }
        go.countDown();
        for (Thread t : ts) {
            t.join();
        }
        Map<String, String> sorted = new TreeMap<>(got);
        long timeouts = sorted.values().stream().filter("TIMEOUT"::equals).count();
        boolean symmetric = sorted.entrySet().stream()
                .filter(e -> !e.getValue().equals("TIMEOUT"))
                .allMatch(e -> sorted.get(e.getValue()).equals(e.getKey()));
        boolean noneGotOwn = sorted.entrySet().stream()
                .noneMatch(e -> e.getKey().equals(e.getValue()));
        System.out.println(threads + " threads: timed out " + timeouts
                + ", pairs symmetric " + symmetric + ", nobody got its own value " + noneGotOwn);
    }
}

Output:

Output
4 threads: timed out 0, pairs symmetric true, nobody got its own value true
3 threads: timed out 1, pairs symmetric true, nobody got its own value true
  • With 4 threads, everyone found a partner. The pairs were symmetric (if t0 got t2's value, t2 got t0's), and no thread got its own value back. Which pairs formed varied from run to run.
  • With 3 threads, one was always left without a partner and timed out. With an untimed exchange, that thread would have waited forever.
  • So if two specific threads must talk, give them their own exchanger. Sharing one between several producers and consumers can pair two producers with each other, swapping two full buffers and never reaching a consumer.

Timeouts, interruption and null values

The untimed exchange waits until a partner comes. The program shows the three ways a wait can end other than a normal swap, and that null is a valid value to exchange.

Java
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ExchangeTimeout {

    public static void main(String[] args) throws InterruptedException {
        Exchanger<String> exchanger = new Exchanger<>();

        // 1. No partner: the timed form gives up
        long t0 = System.nanoTime();
        try {
            exchanger.exchange("anyone there?", 300, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            long ms = (System.nanoTime() - t0) / 100000000 * 100;
            System.out.println("1. no partner after ~" + ms + " ms: TimeoutException");
        }

        // 2. A waiting thread can be interrupted
        Thread waiter = new Thread(() -> {
            try {
                exchanger.exchange("waiting forever");
            } catch (InterruptedException e) {
                System.out.println("2. waiter interrupted: InterruptedException");
            }
        });
        waiter.start();
        Thread.sleep(100);
        waiter.interrupt();
        waiter.join();

        // 3. null is a valid value, for example "I have nothing this round"
        Thread partner = new Thread(() -> {
            try {
                String got = exchanger.exchange("data");
                System.out.println("3. partner received " + got);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        partner.start();
        String got = exchanger.exchange(null);
        partner.join();
        System.out.println("3. main received " + got);
    }
}

Output:

Output
1. no partner after ~300 ms: TimeoutException
2. waiter interrupted: InterruptedException
3. partner received null
3. main received data
  1. exchange(x, 300, MILLISECONDS) gave up after about 300 ms with TimeoutException. The item it offered is not kept, so a later partner does not receive it.
  2. A thread waiting in exchange responds to interrupt() with InterruptedException, like other blocking calls. A pipeline's shutdown logic can therefore interrupt both threads.
  3. Unlike the queues, which reject null, an exchanger accepts it. Main offered null and the partner received null, which can mean "nothing this round" without a placeholder object.

The null value also gives a double-buffer pipeline a clean way to stop: the producer makes its last exchange with null (or an empty list) as an end marker, the consumer leaves its loop when it receives it, and because that final exchange completed on both sides, neither thread is left waiting at the exchanger. Ending with a marker is more reliable than interrupting, which can arrive while a buffer is half processed.

A separate test confirmed the first point: after a timed-out exchange("old"), the next pair of threads swapped only their own values, and "old" was never delivered. When one side of a double buffer fails, the other is left waiting. Use the timed form in both threads, or have the failing thread interrupt its partner, so that a crash does not turn into a hang.

How fast is a hand-off?

Two threads pass 500,000 small values, first through an Exchanger, then a SynchronousQueue, then a bounded ArrayBlockingQueue. Each runs 3 times and the fastest is reported. This is a rough comparison on a 2-CPU machine, not a benchmark.

Java
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Exchanger;
import java.util.concurrent.SynchronousQueue;

public class HandoffSpeed {

    interface Pass {
        void run(int n) throws InterruptedException;
    }

    public static void main(String[] args) throws InterruptedException {
        int n = 500000;
        System.out.printf("%,d hand-offs between two threads, best of 3%n", n);
        time("Exchanger", n, HandoffSpeed::exchanger);
        time("SynchronousQueue", n, HandoffSpeed::synchronousQueue);
        time("ArrayBlockingQueue(1024)", n, HandoffSpeed::arrayQueue);
    }

    static void exchanger(int n) throws InterruptedException {
        Exchanger<Integer> ex = new Exchanger<>();
        Thread other = start(() -> {
            for (int i = 0; i < n; i++) {
                ex.exchange(0);
            }
        });
        for (int i = 0; i < n; i++) {
            ex.exchange(i & 127);
        }
        other.join();
    }

    static void synchronousQueue(int n) throws InterruptedException {
        SynchronousQueue<Integer> q = new SynchronousQueue<>();
        Thread other = start(() -> {
            for (int i = 0; i < n; i++) {
                q.take();
            }
        });
        for (int i = 0; i < n; i++) {
            q.put(i & 127);
        }
        other.join();
    }

    static void arrayQueue(int n) throws InterruptedException {
        ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<>(1024);
        Thread other = start(() -> {
            for (int i = 0; i < n; i++) {
                q.take();
            }
        });
        for (int i = 0; i < n; i++) {
            q.put(i & 127);
        }
        other.join();
    }

    interface Body {
        void run() throws InterruptedException;
    }

    static Thread start(Body body) {
        Thread t = new Thread(() -> {
            try {
                body.run();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        t.start();
        return t;
    }

    static void time(String name, int n, Pass pass) throws InterruptedException {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            pass.run(n);
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("%-26s %,6d ms  %,6.0f ns per hand-off%n",
                name, best / 1000000, (double) best / n);
    }
}

Output (timings from a 2-CPU Linux machine on JDK 21):

Output
500,000 hand-offs between two threads, best of 3
Exchanger                     168 ms     337 ns per hand-off
SynchronousQueue            1,966 ms   3,933 ns per hand-off
ArrayBlockingQueue(1024)       18 ms      37 ns per hand-off
  • The ArrayBlockingQueue was by far the fastest, at tens of nanoseconds per element. Its threads rarely wait for each other: the producer adds many elements while the consumer is still busy, so most operations need no meeting at all.
  • Exchanger and SynchronousQueue require the two threads to meet for every single item, and each meeting can mean parking one thread and waking it again. Their times varied by more than ten times between runs, from a few hundred nanoseconds to several microseconds per hand-off, depending on whether a waiting thread caught its partner while still spinning.
  • The lesson is to exchange large units, as the double buffer does with 1,000 items per swap, and never single values. Per-item rendezvous only makes sense when the waiting itself is the point.

When to use an Exchanger

Choosing a hand-off tool
SituationUse
Two threads alternately fill and drain buffersExchanger with two reusable buffers
Two threads must swap state at a checkpointExchanger, one per pair
Many producers and consumersA bounded BlockingQueue
Recycling buffers among more than two threadsTwo queues: one for full buffers, one for empty ones
Each item must be taken before the producer continuesSynchronousQueue
One thread delivers a single result to anotherCompletableFuture
A group of threads waits for each other without dataCyclicBarrier or Phaser

For the threads themselves, see thread basics; for why the swap is safe without locks, see the Java Memory Model.