Exchanger Timed Handoff And Buffer Reuse
Swap reusable list buffers between producer and consumer with Exchanger, and enforce a bounded wait using timed exchange with TimeoutException.
Code
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class TimedBufferHandoff {
public static void main(String[] args) throws InterruptedException {
Exchanger<List<String>> exchanger = new Exchanger<>();
Thread producer = new Thread(() -> {
List<String> buf = new ArrayList<>();
try {
for (int batch = 1; batch <= 2; batch++) {
buf.add("item-" + batch + "a");
buf.add("item-" + batch + "b");
// Trade full list for consumer's empty list
buf = exchanger.exchange(buf, 500, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException | TimeoutException e) {
Thread.currentThread().interrupt();
}
});
Thread consumer = new Thread(() -> {
List<String> buf = new ArrayList<>();
try {
for (int batch = 1; batch <= 2; batch++) {
buf = exchanger.exchange(buf, 500, TimeUnit.MILLISECONDS);
System.out.println("consumed batch " + batch + ": " + buf);
buf.clear(); // reuse emptied list on next exchange
}
} catch (InterruptedException | TimeoutException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
consumer.start();
producer.join();
consumer.join();
// Unpaired exchange times out cleanly instead of hanging forever
try {
exchanger.exchange(List.of("orphan"), 30, TimeUnit.MILLISECONDS);
} catch (TimeoutException timedOut) {
System.out.println("unpaired exchange timed out as expected");
}
}
}Code mechanics — Exchanger Timed Handoff And Buffer Reuse
Structurally, expect the class TimedBufferHandoff and nothing else.
Repetition is confined to for (int batch = 1; batch <= 2; batch++) — the rest of the file is straight-line.
Points of care
- Having the baseline language compiler or interpreter installed is all that suffices.
Applying it
Printed rows begin with tags — consumed batch, unpaired exchange timed out as expected — when the file runs.
Statements that matter
Thread.currentThread().interrupt();
Interactive Tools for This Topic
FAQ
- What does Exchanger Timed Handoff And Buffer Reuse print when run?
- Execute the whole file; each printed line is prefixed with a label like `consumed batch`, `unpaired exchange timed out as expected`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.