Scrivio Interview library
ConceptIntermediate6 min read · updated 12 November 2026

What does java.util.concurrent.Exchanger do, and describe a situation where it fits.

An Exchanger is a meeting point for two threads: each calls exchange(x), and each receives the object the other passed in. The first thread to arrive waits for its partner, and exchange(x, timeout, unit) limits that wait. It fits double buffering, where a producer fills one buffer while a consumer drains another and they swap when both are ready, but because it only pairs two threads at a time it rarely fits server workloads, and a BlockingQueue of buffers is usually easier to understand.

Why this question is asked

Exchanger is the least used class in java.util.concurrent, and interviewers ask about it partly to see whether we know it exists and partly to see whether we can judge when a niche tool is worth its strangeness. Knowing where it fits, and why it usually does not, says more about our judgement than knowing its methods. In this answer, we will see what exchange() does, walk through the double-buffering pattern with code, look at timeouts and failure, and then compare it with the BlockingQueue design most teams would find easier.

1What exchange() Does

An Exchanger<V> has one important method, exchange(V x). When a thread calls it, one of two things happens. If no partner is waiting, the thread blocks. If a partner is already waiting, the two threads swap: the waiting thread receives our x, we receive the object it passed in, and both continue. It is like two people meeting at a door to swap packages: whoever arrives first waits for the other.

Java
Exchanger<String> ex = new Exchanger<>();
Thread a = Thread.ofPlatform().start(() -> {
String got = ex.exchange("from A"); // waits for B
System.out.println("A got " + got); // A got from B
});
Thread b = Thread.ofPlatform().start(() -> {
String got = ex.exchange("from B");
System.out.println("B got " + got); // B got from A
});
Step throughTwo threads swap at the Exchanger
Thread AExchangerThread B
exchange("from A")
no partner yet: A waits
exchange("from B")
returns "from B"
returns "from A"

5 messages in order. Play them, or step through them one at a time.

(exchange() throws InterruptedException, which the real code must handle.) Notice that the exchange is symmetric: neither thread is a producer or a consumer from the Exchanger's point of view. Each exchange is also a memory synchronization point, so everything thread A wrote into its object before the exchange is visible to thread B after it.

2Where It Fits: Double Buffering

The classic use is double buffering. A producer thread fills a buffer, for example reading records from a file, while a consumer thread drains another buffer, for example writing them to a database. When the producer's buffer is full and the consumer's is empty, they swap. Two buffers are reused forever, no new buffers are allocated, and the two threads run in parallel most of the time.

Java
Exchanger<List<Record>> ex = new Exchanger<>();
Runnable producer = () -> {
List<Record> buf = new ArrayList<>(1000);
while (reader.hasNext()) {
buf.add(reader.next());
if (buf.size() == 1000) buf = ex.exchange(buf); // hand over full, receive empty
}
ex.exchange(buf); // last, partly filled buffer (end-of-data handling omitted)
};
Runnable consumer = () -> {
List<Record> buf = new ArrayList<>(1000);
while (true) {
buf = ex.exchange(buf); // hand over empty, receive full
writer.writeBatch(buf); // 1000 records
buf.clear();
}
};

Notice that each thread always holds exactly one buffer, and ownership changes only at the exchange. That is what makes the pattern safe without any other locking: no buffer is ever touched by two threads at the same time. The cost is that the two threads are tied in lockstep: if the writer is slower than the reader, the producer waits at every swap, and the pipeline runs at the speed of the slower side, with only one batch of overlap.

3Timeouts and What Happens When a Partner Never Comes

The plain exchange() waits forever. If the consumer thread dies, the producer blocks at its next swap and the program hangs. exchange(x, timeout, unit) bounds the wait and throws TimeoutException if no partner arrives in time. Unlike CyclicBarrier, there is no broken state: a timeout affects only the thread that timed out, and the Exchanger can be used again.

Java
try {
buf = ex.exchange(buf, 30, TimeUnit.SECONDS);
} catch (TimeoutException e) {
log.error("consumer did not take a buffer in 30 s"); // decide: retry, stop, or report
}

End of data needs a plan too. Since both threads only ever exchange, the producer must tell the consumer that the stream has ended, for example by sending a buffer with a marker or by setting a shared flag before the final exchange. This kind of protocol detail is part of why the class is used rarely.

4Why It Rarely Fits Server Code

An Exchanger pairs exactly two threads at a time. Server workloads are usually many-to-many: many request threads produce work and a pool of workers consumes it, and threads come and go. With more than two threads calling exchange(), they pair up in whatever order they arrive, so two producers can swap full buffers with each other, which is almost never what we want. Under contention the implementation spreads threads across an arena of slots to reduce collisions, but the pairing is still arbitrary.

It is also hard to read. A reviewer has to understand the swap protocol, the ownership rules and the end-of-data signal to know the code is correct.

5The Usual Alternative: A BlockingQueue of Buffers

The same double-buffering effect is easier to express with two queues: one for full buffers going to the consumer and one for empty buffers coming back. Each side takes a buffer from one queue and puts it on the other. With more than two buffers in circulation, the producer can run ahead of a temporarily slow consumer, and the design extends naturally to several producers or consumers.

Exchanger and a pair of queues
AspectExchangerTwo BlockingQueues
Threadsexactly two per swapany number of producers and consumers
Buffers in circulationtwoas many as we choose
Slack between the sidesnone, lockstepbounded by the number of buffers
End of datacustom protocola poison-pill buffer is a common idiom
Readabilityneeds explanationfamiliar to most Java developers

6Follow-up questions

Is an Exchanger the same as a SynchronousQueue?

They are related: both hand an object between threads with no buffer in between. But a SynchronousQueue is one-directional, a producer puts and a consumer takes, while an Exchanger is symmetric and both sides give and receive. Notably, both are implemented with their own algorithms rather than on AQS.

What about genetic algorithms or other pairwise swaps?

Those are the other textbook use: two worker threads swap candidate solutions or partial results at fixed points. It is a valid fit, because the work really is pairwise, but it is still mostly found in compute code, not in services.

Does exchange() work with virtual threads?

Yes. A virtual thread waiting in exchange() parks, which unmounts it from its carrier, so waiting is cheap. The design limits of pairing two threads still apply.

7Conclusion

In this answer, we saw that an Exchanger lets two threads swap objects at a meeting point: the first to arrive waits, and exchange(x, timeout, unit) bounds that wait without breaking the Exchanger for later use. It fits double buffering, where a producer and a consumer swap a full buffer for an empty one and each thread always owns exactly one buffer. Because it only pairs two threads in lockstep and needs custom end-of-data handling, it rarely fits server workloads, and a pair of BlockingQueues circulating buffers is usually easier to understand and extend.

What to say in the interviewAbout 80 seconds aloud

Open with

An Exchanger is a meeting point for exactly two threads. Each calls exchange with an object and gets back the object the other one passed in. Whoever arrives first waits for its partner, and there's a timed version, exchange with a timeout, that throws TimeoutException if nobody comes, without breaking the Exchanger for later use, unlike a CyclicBarrier.

Then, if they want more

Each exchange is also a happens-before point, so whatever one thread wrote into its object is visible to the other after the swap. The textbook fit is double buffering: a producer fills a buffer from a file while the consumer writes another to the database, and when the producer's buffer is full they swap full for empty.

Each thread always owns exactly one buffer, so there's no other locking, and only two buffers are ever allocated. But I'd rarely use it in service code. It only pairs two threads, so with more callers they pair up arbitrarily, the two sides run in lockstep with no slack, and you need your own end-of-data protocol.

Usually I'd write the same thing with two BlockingQueues, one for full buffers and one for empty ones, which most developers can read immediately, lets you have more buffers in circulation, and scales to several producers or consumers.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What does java.util.concurrent.Exchanger do, and describe a situation where it fits.": https://scrivio-interview-library.netlify.app/java/synchronizers/55ad5b918c/