JavaRush /Java Blog /Random EN /SynchronousQueue Example in Java - Solving Producer Consu...
profeg
Level 18

SynchronousQueue Example in Java - Solving Producer Consumer Problem

Published in the Random EN group
SynchronousQueue Example in Java - Solving Producer Consumer Problem
SynchronousQueue is a special type of BlockingQueue in which each insert operation must wait for a corresponding remove command in another thread, and vice versa. When you call the put() method on a SynchronousQueue, it blocks until another thread retrieves that element from it. Accordingly, if another thread tries to remove an element from it, and the element is not there, then this thread blocks until the other thread puts the element into the queue. You can think of SynchronousQueue as an athlete ( thread ) running with an Olympic torch, he runs with a torch (an object that is being passed) and passes it to another athlete waiting on the other side. If you pay attention to the name, you will understand that SynchronousQueue is so named for a reason, itpasses data in a synchronized manner to another thread ; it waits for someone to retrieve the data instead of just putting it in and exiting (an asynchronous operation). If you are familiar with CSP and Ada, then you know that synchronized queues are like threads meeting. They are well-suited for control transfer constructs, in which an object running on one thread must synchronize with an object on another thread in order to pass some information, event, or task to it. In the previous multi-threaded programming tutorials, we learned how to solve the producer-consumer problem using the wait and notify methods , and BlockingQueue . We will now learn how to apply the producer-consumer pattern using the SynchronousQueue.This class additionally supports fair behavior for producer and consumer thread wait ordering. By default, this ordering is not guaranteed. However, queues created with fair properties guarantee access for threads in a FIFO (Firs In First Out) queue.
Producer consumer using SynchronousQueue in Java.
Example of SynchronousQueue in Java - solving the problem Producer Consumer - 1 As I said above, there is nothing better than the producer-consumer task of understanding inter-thread interaction.in any programming language. In this problem, one thread acts as a producer that produces events and jobs, and another thread acts as a consumer of this. The shared buffer is used to transfer data from the producer to the consumer. The complexity of solving this problem comes in extreme cases, for example, when the manufacturer is forced to wait because. the buffer is full or the consumer has to wait because buffer is empty. This was easily solved, because. The blocking queue provided not only a buffer to store data, but also flow control, blocking the thread calling the put() method (Producer) if the buffer was full, and blocking the thread calling the take() method (Consumer) if the buffer was empty. Now we will solve the same problem using SynchronousQueue, a special kind of parallel collections.with zero capacity. In the following example, we have two threads called PRODUCER and CONSUMER (always give names to threads, this is a very good style of multi-threaded programming). The first thread places the score in the game, and the second thread consumes it. The score in the game is nothing but an object of type String. But if you run the program with a different type, you won't notice any difference. To understand how SynchronousQueue works and how to solve the producer-consumer problem, you need to: either run the program for debugging (debug) in the Eclipse environment, or simply start the producer thread by commenting out consumer.start(); if the consumer thread is not running then the producer thread will be blocked on queue.put(event); if running, you won't be able to see the [PRODUCER] publish a :FOUR event. This happens because the specific behavior of SynchronousQueue , which guarantees that a thread placing data will be blocked until another thread collects this data, and vice versa. You can test the rest of the code by commenting out producer.start(); and starting only the consumer thread. If you carefully examine what the program outputs, you will notice that the output order is reversed. It looks like the [CONSUMER] thread took the data before the [PRODUCER] thread import java.util.concurrent.SynchronousQueue; /** * Java Program to solve Producer Consumer problem using SynchronousQueue. A * call to put() will block until there is a corresponding thread to take() that * element. * * @author Javin Paul */ public class SynchronousQueueDemo{ public static void main(String args[]) { final SynchronousQueue queue = new SynchronousQueue (); Thread producer = new Thread("PRODUCER") { public void run() { String event = "FOUR"; try { queue.put(event); // thread will block here System.out.printf("[%s] published event : %s %n", Thread .currentThread() .getName(), event); } catch (InterruptedException e) { e.printStackTrace(); } } }; producer.start(); // starting publisher thread Thread consumer = new Thread("CONSUMER") { public void run() { try { String event = queue.take(); // thread will block here System.out.printf("[%s] consumed event : %s %n", Thread .currentThread() .getName(), event); } catch (InterruptedException e) { e.printStackTrace(); } } }; consumer.start(); // starting consumer thread } } Output: [CONSUMER] consumed event : FOUR [PRODUCER] published event : FOUR produced them. This is because, by default, SynchronousQueue does not guarantee queuing. But it has fairness rules that set access to threads in FIFO order. You can enable these rules by passing true to the overloaded SynchronousQueue constructor like so: new SynchronousQueue(boolean fair).
Things to remember about SynchronousQueue in Java.

There are several important properties of this special type of blocking queue in Java. It is very useful to pass data from one thread to another in a synchronized manner. This queue has no capacity and is blocked until another thread releases it.

  1. The SynchronousQueue is blocked, and until one thread is ready to take the data, the other will try to put the data.
  2. SynchronousQueue has no scope. That is, it contains no data.
  3. SynchronousQueue is used to implement a forward transfer queuing strategy where a thread transfers control to a waiting thread, or creates a new one if allowed, otherwise no control is transferred.
  4. This queue does not pass null data. Attempting to add a null element will throw a NullPointerException .
  5. If you use other methods from the Collection (such as contains), the SynchronousQueue behaves like an empty collection.
  6. You can't use the peek method on a SynchronousQueue because the element only exists when you try to remove it; also, you won't be able to insert elements (using any method) unless another thread tries to remove it.
  7. You won't be able to use an iterator on a SynchronousQueue because it has no elements.
  8. SynchronousQueue can be created with fair rules, where access to threads is guaranteed in FIFO order.
Perhaps this is all about SynchronousQueue in Java. We looked at some of the special features of this multi-threaded collection, and learned how to solve the classic producer-consumer problem using SynchronousQueue in Java. By the way, calling it a Queue is not quite right, because. it has no elements. The call to the put() method will not complete until another thread calls the take() method. It is more correct to think of it as a meeting place for threads, where they share an object. In other words, this is Java's synchronized object passing utility, perhaps a safer alternative to the wait and notify method .
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION