Java SynchronousQueue

In this tutorial, we will learn about java.util.concurrent.SynchronousQueue, its features along with the working examples including explanation of those.

SynchronousQueue

In Java, SynchronousQueue is class which is an implementation of the BlockingQueue unlike other implementations of BlockingQueue, SynchronousQueue does not have any initial capacity not even a 0. At a time only one producer can produce a single message in case only any of the thread is waiting to consume the message.

Features of SynchronousQueue and example:

This kind of implementation is useful for scenarios where producing depends upon the consumption of messages.

SynchronousQueue example:

CopiedCopy Code
import java.util.concurrent.SynchronousQueue;
public class SynchronousQueueExample extends Thread {
	public SynchronousQueue<String> synQueue;
	public String threadName;
	public SynchronousQueueExample(SynchronousQueue<String> synQueue, String threadName) {
		super(threadName);
		this.synQueue = synQueue;
		this.threadName = threadName;
	}
	public static void main(String[] args) throws InterruptedException {
		SynchronousQueue<String> syncQueue = new SynchronousQueue<>();
		new SynchronousQueueExample(syncQueue, "producer").start();
		System.out.println("Message consumed :"+syncQueue.take());
		System.out.println("Message consumed :"+syncQueue.take());
	}
	@Override
	public void run() {
		try {
			this.synQueue.put("message 1");
			System.out.println("Produced message 1 successfully");
			this.synQueue.put("message 2");
			System.out.println("Produced message 2 successfully");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

Output:

Produced message 1 successfully
Message consumed :message 1
Produced message 2 successfully
Message consumed :message 2

Explanation :

In the above example, we have created a SynchronousQueue class to accept the String type elements. Created a thread of producing the messages and main thread will consume the produced messages. As there is no mechanism of queue capacity hence once the message produced then the message got consumed at main thread level.

Conclusion :

In this tutorial, we have covered what is the SynchronousQueue and its unique feature along with the working example of it.