How does SynchronousQueue hand over an element with no capacity: where does a blocked put() wait, why is size() 0, and when does offer() fail?
answer
- a list of waiters, not a buffer
- one node per blocked call
- atomic write on the node's item
- size() never reads that list
- offer() passes a wait of zero
basics
~20 sIn SynchronousQueue, a blocked put() or take() waits in its own node on a private transfer list. size() is hard-coded to 0, and offer() adds no node: it succeeds only by matching a consumer already waiting.
solid answer
~50 s`SynchronousQueue` has no capacity, but it does have a list of waiters: a private `transferer`, a `LinkedTransferQueue` subclass used as a stack by default and as a FIFO queue when fair. A `put()` with no consumer waiting pushes a `DualNode` holding the element and parks; a `take()` with no producer waiting pushes an empty request node and parks. The next caller with the opposite role changes that node's `item` by CAS and unparks the waiter, so the element goes straight from one thread to the other. `size()` is a literal `return 0` that never looks at the list, so it stays 0 however many producers are blocked. `offer(e)` is the same transfer with a zero wait: it can match a node already there but never adds one, so it returns `false` unless a consumer is already waiting.
code
java · 39 linesimport java.util.concurrent.SynchronousQueue;
public class HandOff {
public static void main(String[] args) throws Exception {
SynchronousQueue<String> q = new SynchronousQueue<>();
System.out.println(q.offer("a")); // false: no consumer is waiting
Thread producer = new Thread(() -> {
try {
q.put("b");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
while (producer.getState() != Thread.State.WAITING) {
Thread.onSpinWait(); // until the producer has parked in put()
}
System.out.println(q.size()); // 0, with a producer blocked in put()
System.out.println(q.peek()); // null
System.out.println(q.take()); // b, from the waiting producer
producer.join();
Thread consumer = new Thread(() -> {
try {
System.out.println(q.take()); // c
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
consumer.start();
while (consumer.getState() != Thread.State.WAITING) {
Thread.onSpinWait(); // until the consumer has parked in take()
}
boolean accepted = q.offer("c"); // matches the waiting take()
consumer.join();
System.out.println(accepted); // true
}
}go deeper
Recall the contract: no capacity, and each put() needs a matching take(). size() is always 0, peek() is always null, and offer() returns false when nobody is waiting to receive.
Explain the waiting list: one node per blocked call, holding the element or an empty request, matched by a CAS on its item and an unpark. Show offer() as the same transfer with a zero wait, which adds no node.
Apply it in production: a queue-depth metric reads 0 on this class whatever the backlog, so look at blocked threads and pool rejections instead. Expect offer() to fail while consumers are merely busy between takes.
Weigh direct hand-off against a buffer: nothing sits queued, so backpressure is immediate, but bursts must be absorbed by more threads or by rejections. Decide who owns that overflow policy, and whether the default's unspecified order suits the work.
## No capacity does not mean no memory The Javadoc says a `SynchronousQueue` "does not have any internal capacity, not even a capacity of one". That is a promise about behaviour: you cannot leave an element in the queue for someone to collect later. It does not mean no object is involved. While a producer waits, its element is referenced from a node that belongs to that one waiting call. Three terms describe the design: - A **dual data structure** holds either data nodes, which carry producers' elements, or request nodes, which are slots for consumers. The source describes it as holding one kind or the other at any given time, or being empty. - A **fulfilling operation** is a call that meets a node of the opposite kind and completes it. - A **hand-off** is the result: one thread's element reaches another thread, and nothing stays behind. ## Where a waiting `put` or `take` sits Each queue has a private field `transferer` of the package-private nested class `Transferer`, which extends `LinkedTransferQueue`. A waiting call is one package-private `DualNode`: - `item`: the element for a waiting `put`, `null` for a waiting `take`. - `isData`: `true` for a producer's node, `false` for a consumer's. - `waiter`: the thread to wake, set just before it parks. - `next`: the link to the next node. The constructor decides how those nodes are arranged: | | `new SynchronousQueue()` | `new SynchronousQueue(true)` | |---|---|---| | Method | `xferLifo`, added by `Transferer` | `xfer`, inherited from `LinkedTransferQueue` | | Shape | Stack, with `head` as the top | FIFO queue | | Matched first | Most recent waiter | Longest waiter | | Public promise | Order is not guaranteed | FIFO order | These names are JDK 27's implementation, and `SynchronousQueue.java` is identical in JDK 25. The source mentions "multiple implementation overhauls", so an older description may name other classes. The shape is what stays useful: a list of waiting threads, not a buffer of elements. ## One hand-off, step by step `put`, `take`, `offer` and `poll` all call a private `xfer(e, nanos)`. `e` is the element, or `null` for a consumer, and `nanos` is how long the caller may wait. Suppose a consumer calls `take()` on an idle default queue, and a producer then calls `put(x)`: 1. The consumer finds no data node, pushes a request node with `item == null` and waits. 2. The producer sees a request node on top and uses compare-and-exchange (CAS) to change its `item` from `null` to `x`. This one atomic write is the hand-off. If two producers race, one loses and retries. 3. The producer pops the node, calls `LockSupport.unpark` on `waiter`, and `put` returns. 4. The consumer sees that `item` is no longer `null`, and `take` returns `x`. Steps 3 and 4 can happen in either order, because the consumer may already be awake: a waiter may spin briefly before it sets `waiter` and parks. If the producer arrives first, the roles mirror: its node holds `x`, and the consumer's CAS changes `item` from `x` to `null`. A waiter that is interrupted or times out tries a CAS on its own node, racing any match. If it wins, the node is dead and gets unlinked; if the match won, the transfer stands. ## Why `size()` is always 0 `size()` is not computed from anything. Its body is `return 0;`, and it never looks at `transferer`. Its neighbours are hard-coded in the same way: - `isEmpty()` returns `true`, `remainingCapacity()` returns 0 and `peek()` returns `null`. - `contains(o)` and `remove(o)` return `false`, and `clear()` does nothing. - `iterator()` is empty and `toString()` returns `[]`. This is the contract: for those `Collection` methods the queue acts as an empty collection. So a hundred blocked producers still report `size() == 0`, `clear()` releases none of them, and a queue-depth metric on this class tells you nothing. ## Why `offer(e)` fails unless a consumer is waiting `offer(e)` returns `xfer(e, 0L) == null`. A wait of `0L` means **immediate mode**. In `xferLifo`, the check `if (ns == 0L)` comes before any node is created, so with no request node to match it hands back `e`, and `offer` returns `false`. The fair path also declines to add a node when the wait is 0. The overloads differ in the wait they pass: | Call | Wait passed | With no opposite node | |---|---|---| | `put(e)`, `take()` | `Long.MAX_VALUE` | Adds a node and waits | | `offer(e, t, unit)`, `poll(t, unit)` | `t` in nanoseconds | Adds a node if `t` is positive; `false` or `null` when time runs out | | `offer(e)`, `poll()` | `0L` | Adds no node; `false` or `null` | **Already waiting** has an exact meaning: a request node is on the list, left by `take()` or a timed `poll`. A consumer thread between two `take()` calls has no node, so `offer` can fail while consumers look healthy. Two `offer` calls never match each other either, because both carry data, and `poll()` mirrors all of this against waiting producers.
- Why does the default SynchronousQueue match the most recent waiter, and when would you pass true to the constructor?Non-fair mode keeps waiters on a stack, so `xferLifo` matches the top node. The source calls LIFO generally preferable in resource management settings such as cached thread pools, for temporal locality, and inappropriate for message passing. Pass `true` when arrival order matters: that mode grants access in FIFO order. The public contract says only that the default order is not guaranteed.
- What happens to the element when a producer blocked in SynchronousQueue.put() is interrupted?The waiter tries to change its node's `item` from the element to `null`. If that wins, the node is unlinked, `put` clears the interrupted flag and throws `InterruptedException`, and no consumer received the element. If a consumer's match won first, `put` returns normally with the flag still set, and the element was delivered.
- Can SynchronousQueue.drainTo() return anything when size() reports 0?Yes. `drainTo` loops on `poll()`, and `poll()` can match a producer already waiting, so it can collect elements from blocked producers even though `size()` says 0. It stops at the first `poll()` that returns `null`, so it does not wait for a producer that arrives a moment later.
- What does SynchronousQueue.offer(x, 0, TimeUnit.SECONDS) do, and how does it differ from offer(x)?It passes a zero wait too, because the timed overload floors the timeout at 0, so a zero or negative timeout adds no node and returns `false` unless a consumer is already waiting. The difference is interruption: if the caller's interrupted flag is set and no match happens, the timed form clears it and throws `InterruptedException`, while `offer(x)` never checks it and returns `false`.
A relay changeover with no table to put the baton on. A runner who arrives first stands holding the baton, and counting batons on the table gives zero however many runners are standing there. offer() is a runner who hands over only if a hand is already out, and otherwise walks away still holding it.
- SynchronousQueue stores one element at a time, so it behaves like a queue of capacity one.
- size() returns the number of producers currently blocked in put().
- offer(e) waits briefly for a consumer to show up before it returns false.
- offer(e) leaves the element in the queue so the next take() can pick it up.
- No data structure is involved; threads signal each other directly and share nothing.
- The no-argument constructor matches waiters in FIFO order.
- SynchronousQueue
- Java 1.5
- LinkedTransferQueue
- Java 1.7
- LockSupport
- Java 1.5
Assumes JDK 27; the internals named here are implementation, not contract, and SynchronousQueue's source is identical in JDK 25.
context
- SynchronousQueue (Java SE 27 & JDK 27)docs.oracle.com
- SynchronousQueue.java at jdk-27-gagithub.com
- LinkedTransferQueue.java at jdk-27-gagithub.com