Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

SynchronousQueue — handoff without a buffer

SynchronousQueue transfers an element directly between threads. Its put and take operations wait for a matching partner rather than using a buffer.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

SynchronousQueue<E> queue = new SynchronousQueue<>();

// Producer thread:
queue.put(value); // throws InterruptedException

// Consumer thread (a different thread using the same queue):
E valueReceived = queue.take(); // throws InterruptedException

SynchronousQueue<E> in java.util.concurrent is a blocking queue with no capacity, not even one slot. It pairs a producer with a consumer instead of storing elements.

SynchronousQueue.put waits until another thread receives the element; SynchronousQueue.take waits for a handoff and returns the element. Without a consumer, put blocks the calling thread. While put is waiting, that thread cannot reach its subsequent take call, but other threads can continue running. Completion of put does not mean processing has finished.

Both methods can throw InterruptedException while waiting. Do not ignore interruption: propagate the exception or restore the interrupt flag and end the task. null is forbidden. size() always returns 0, and peek() always returns null.

The example separates put and take across two threads. It prints hello, then size=0, regardless of their starting order.

Examples

import java.util.concurrent.SynchronousQueue;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        SynchronousQueue<String> queue = new SynchronousQueue<>();
        Thread producer = new Thread(() -> {
            try {
                queue.put("hello");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        producer.start();
        try {
            String value = queue.take();
            producer.join();
            System.out.println(value);
            System.out.println("size=" + queue.size());
        } finally {
            producer.interrupt();
            producer.join();
        }
    }
}

Result

hello
size=0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources