Exchanger pairs two threads so each hands over one object and receives the other's object. A missing partner means waiting, timeout, or interruption rather than queued delivery.
Java Exchanger: swap buffers at a two-party rendezvous
Operational contract
A producer and consumer can exchange ownership of same-size byte buffers after each processing stage. The timed call bounds how long this method waits for a partner. Neither side may keep mutating the buffer it hands away after a successful exchange; the recipient now owns it. The exchanger passes object references, not copies. A timeout means this method did not complete an exchange, so the caller retains its original buffer and must decide whether to retry or stop. This sample has exactly two participants by contract.
Failure case
One worker fills a 47-byte parcel label buffer while another has an empty 47-byte buffer ready. They meet and swap. If the second worker fails before reaching the rendezvous, the first returns through a timeout rather than blocking forever.
Java code
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class ParcelBufferSwap {
private final Exchanger<byte[]> buffers = new Exchanger<>();
public byte[] swap(byte[] ownedBuffer) throws InterruptedException, TimeoutException {
if (ownedBuffer.length != 47) throw new IllegalArgumentException("Expected 47 bytes");
byte[] received = buffers.exchange(ownedBuffer, 3, TimeUnit.SECONDS);
if (received.length != 47) throw new IllegalStateException("Partner used wrong buffer size");
return received;
}
}Performance and ownership cost
The exchange transfers references in O(1) application work and requires two live participants; scheduling and contention control actual latency. Both 47-byte arrays already exist. It is not a queue or a capacity policy for arbitrary producer volume.
Common Mistakes
- Do not retain write ownership of a buffer after handing it over.
- Do not assume the partner always arrives; handle timeout and interruption.
- Do not use a two-party exchanger as a many-message backlog.
