SynchronousQueue in Java

SynchronousQueue in Java is an implementation of BlockingQueue interface and is part of java.util.concurrent package. SynchronousQueue in Java is different from other BlockingQueue implementations like ArrayBlockingQueue and PriorityBlockingQueue because a synchronous queue does not have any internal capacity, not even a capacity of one. So, each insert operation in SynchronousQueue must wait for a corresponding remove operation by another thread, and vice versa.

That is why it is named SynchronousQueue as the hand-off of the element happens synchronously rather than inserting the data that can be retrieved asynchronously.

Features of SynchronousQueue in Java

  1. SynchronousQueue doesn’t have any internal capacity, not even one.
  2. Since there is no capacity each insert operation must wait for a corresponding remove operation by another thread. For example if you insert an element to synchronous queue using put() method the method is blocked until another thread receives that element. Same way if you are trying to retrieve an element from the synchronous queue and there is no element in the queue method waits for another thread to insert it.
  3. You cannot peek at a synchronous queue because an element is only present when you try to remove it. So the peek() method always returns null.
  4. SynchronousQueue can’t be iterated as there is nothing to iterate. So the iterator() and spliterator() methods return an empty iterator or spliterator respectively.
  5. SynchronousQueue in Java, just like other BlockingQueue implementations, does not permit null elements. It throws NullPointerException on attempts to add, put or offer a null.

Java SynchronousQueue constructors

  • SynchronousQueue()– Creates a SynchronousQueue with nonfair access policy.
  • SynchronousQueue(boolean fair)– Creates a SynchronousQueue with the specified fairness policy. A SynchronousQueue constructed with fairness set to true grants threads access in FIFO order.

SynchronousQueue Java example

BlockingQueue implementations are designed to be used primarily for producer-consumer queues so let’s see an example of producer-consumer using SynchronousQueue. In the example two threads are created one a producer thread and another a consumer thread.

In the consumer thread delay of 3 seconds is introduced using the sleep() method before taking the element out of the synchronous queue but the put() method waits until the elements is retrieved rather than trying to add another element.

Output

That’s all for the topic SynchronousQueue in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.