Video in progress

Strong Middle 🧵 Concurrency

Why is SynchronousQueue called a "zero-capacity" queue, and where is it used?

SynchronousQueue stores nothing: a thread that does put waits until someone does take. It's a hand-to-hand handoff. Its best-known use is in newCachedThreadPool: a task is given to an idle thread right away, and if there's no idle thread, a new one is started.

📖 Answer

An ordinary queue is a buffer: the producer drops the item and leaves. SynchronousQueue has no buffer, so the two sides have to meet:

SynchronousQueue<String> q = new SynchronousQueue<>();

Thread.ofPlatform().start(() -> {
    try {
        q.put("buyurtma-1");          // stays here until a consumer takes it
        System.out.println("topshirildi");
    } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});

String order = q.take();              // at this moment both continue

offer(e), on the other hand, doesn't wait: if no thread is sitting in take/poll at that moment, it returns false. ThreadPoolExecutor uses exactly this:

// inside newCachedThreadPool
new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, SECONDS, new SynchronousQueue<>());

When a task arrives, the executor calls offer. If an idle worker is sitting in poll, the task goes to it. If not, offer fails and the executor starts a new thread, or rejects the task if it has reached the max. So SynchronousQueue plus a small maximumPoolSize plus CallerRunsPolicy gives you an easy-to-understand pool: "no queue, and when it's full the caller runs the task itself".

size() is always 0, peek() is always null, and iteration is empty, so don't expect these to mean anything in monitoring. There's also a fair mode: new SynchronousQueue<>(true) serves waiters in FIFO order.

A close relative is Exchanger: two threads meet at a point and swap objects (for example, a full buffer for an empty one). It's rare in practice, but interviewers sometimes ask about it.