March 15, 2024

SynchronousQueue in Java With Examples

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.

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;

public class SychroQ {
  public static void main(String[] args) {
    BlockingQueue<Integer> bQueue = new SynchronousQueue<>();
    // Producer 
    new Thread(()->{
      for(int i = 0; i < 5; i++){
        try {
          System.out.println("Added to queue-" + i);
          bQueue.put(i);
          Thread.sleep(200);                                 
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        }
    }).start();
        
    // Consumer
    new Thread(()->{
      for(int i = 0; i < 5; i++){
        try {
          Thread.sleep(3000);
          System.out.println("Consumer retrieved- " + bQueue.take());                    
          
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
      }
    }).start();
  }
}
Output
Added to queue-0
Consumer retrieved- 0
Added to queue-1
Consumer retrieved- 1
Added to queue-2
Consumer retrieved- 2
Added to queue-3
Consumer retrieved- 3
Added to queue-4
Consumer retrieved- 4

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


You may also like

No comments:

Post a Comment