SynchronousQueue Direct Handoff
Hand work straight from producer to consumer with a zero-capacity queue: put() blocks until another thread takes, so nothing is buffered in between.
Code
import java.util.concurrent.SynchronousQueue;
public class JobHandoff {
public static void main(String[] args) throws InterruptedException {
// 零容量队列:任何 put 都必须等到另一线程恰好 take,中间不缓冲
SynchronousQueue<String> handoff = new SynchronousQueue<>();
Thread worker = new Thread(() -> {
try {
while (true) {
String job = handoff.take();
System.out.println("worker picked up: " + job);
}
} catch (InterruptedException stopped) {
System.out.println("worker interrupted, exiting");
}
});
worker.start();
for (String job : new String[] {"reindex-a", "reindex-b"}) {
System.out.println("submitting: " + job);
handoff.put(job); // 阻塞到 worker take 才返回
System.out.println("confirmed handoff: " + job);
}
worker.interrupt();
worker.join();
System.out.println("worker finished: " + !worker.isAlive());
}
}How it works
The working surface is the class JobHandoff — everything else is wiring.
Iteration happens inside while (true) — everything outside it runs once.
Applying it
The run emits 5 labeled sections — worker picked up:, worker interrupted, exiting, submitting:, confirmed handoff:, worker finished: — one per step.
Statements that matter
Thread worker = new Thread(() -> {
try {
while (true) {
String job = handoff.take();
System.out.println("worker picked up: " + job);
}
} catch (InterruptedException stopped) {
System.out.println("worker interrupted, exiting");
}
});
Interactive Tools for This Topic
FAQ
- What does SynchronousQueue Direct Handoff print when run?
- No setup needed: run the file and look for labeled lines like `worker picked up:`, `worker interrupted, exiting`, `submitting:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.