What is a Synchronous Queue in Java?

By | March 7, 2023

A SynchronousQueue in Java is a blocking queue that can be used to pass objects between threads in a synchronous manner. It has no capacity, meaning that each put() operation must be matched by a corresponding take() operation from a different thread, otherwise the thread performing the put() operation will block until another thread performs a take() operation.

The SynchronousQueue is called synchronous because the put() and take() methods block until the corresponding method is called by another thread. This makes it useful in scenarios where there is a one-to-one relationship between the producer and the consumer threads.

Here is an example of how to use a SynchronousQueue to pass messages between two threads

import java.util.concurrent.SynchronousQueue;

public class Example {
public static void main(String[] args) {
SynchronousQueue<String> queue = new SynchronousQueue<>();

Thread producer = new Thread(() -> {
try {
String message = “Hello”;
queue.put(message);
System.out.println(“Producer: ” + message);
} catch (InterruptedException e) {
e.printStackTrace();
}
});

Thread consumer = new Thread(() -> {
try {
String message = queue.take();
System.out.println(“Consumer: ” + message);
} catch (InterruptedException e) {
e.printStackTrace();
}
});

producer.start();
consumer.start();
}
}

In this example, a SynchronousQueue is created and passed between a producer thread and a consumer thread. The producer thread puts a message “Hello” into the queue using the put() method, which blocks until the consumer thread performs a corresponding take() operation. The consumer thread takes the message from the queue using the take() method, which blocks until a message is available, and then prints it to the console.

Note that the SynchronousQueue does not have any capacity, so if the take() method is called before the put() method, the consumer thread will block until a message is available in the queue. Similarly, if the put() method is called before the take() method, the producer thread will block until the message is taken from the queue. This makes SynchronousQueue a useful tool for synchronizing threads in a one-to-one relationship.

Leave a Reply

Your email address will not be published. Required fields are marked *