Synchronousqueue Illustration Inward Coffee - Produer Consumer Solution

SynchronousQueue is particular sort of BlockingQueue in which each insert functioning must expect for a corresponding take away functioning yesteryear about other thread, too vice versa. When y'all telephone band put() method on SynchronousQueue it blocks until about other thread is in that place to possess got that chemical constituent out of the Queue. Similarly, if a thread tries to take away an chemical constituent too no chemical constituent is currently present, that thread is blocked until about other thread puts an chemical constituent into the queue. You tin correlated SynchronousQueue with athletes (threads) running amongst Olympic torch, they run amongst torch (object demand to endure passed) too passes it to other athlete waiting at other end.

If y'all pay attending to the name, y'all volition every bit good empathize that it is named SynchronousQueue with a reason, it passes information synchronously to other thread; it expect for the other political party to possess got the information instead of simply putting information too returning (asynchronous operation).

If y'all are familiar amongst CSP and Ada, too thus y'all know that synchronous queues are like to rendezvous channels. They are good suited for hand-off designs, inwards which an object running inwards i thread must sync upwardly amongst an object running inwards about other thread inwards gild to manus it about information, event, or task.

In before multi-threading tutorials nosotros possess got learned how to solve producer consumer work using wait too notify, and BlockingQueue and inwards this tutorial nosotros volition larn how to implement producer consumer pattern pattern using synchronous queue.

This shape every bit good supports an optional fairness policy for ordering waiting producer too consumer threads. By default, this ordering is non guaranteed. However, a queue constructed amongst fairness belongings laid to truthful grants threads access inwards FIFO order.



Producer Consumer using SynchronousQueue inwards Java

As I possess got said before, nil is meliorate than a producer consumer work to empathize inter-thread communication inwards whatsoever programming language. In Producer consumer problem, i thread human activeness every bit producer which produces lawsuit or business too other thread human activeness every bit consumer. Shared buffer is used to transfer information from producer to consumer.

Difficulty inwards solving producer consumer work comes amongst border cases e.g. producer must expect if buffer is total or consumer thread must expect if buffer is empty.  Later i was quite slowly every bit blocking queue provides non alone buffer to shop information but every bit good time period command to block thread calling put() method (PRODUCER) if buffer is full, too blocking thread calling take() method (CONSUMER) if buffer is empty.

In this tutorial, nosotros volition solve the same work using SynchronousQueue, a particular sort of concurrent collection which has null capacity.

in which each insert functioning must expect for a corresponding take away functioning yesteryear about other t SynchronousQueue Example inwards Java - Produer Consumer Solution

In next example, nosotros possess got 2 threads which is named PRODUCER and CONSUMER (you should ever cite your threads, this is i of the best do of writing concurrent application).

First thread, publishing cricket score, too minute thread is consuming it. Cricket scores are nil but a String object here.

If y'all run the plan every bit it is y'all won't reveal whatsoever matter different. In gild to empathize how SynchronousQueue works, too how it solves producer consumer problem, y'all either demand to debug this plan inwards Eclipse or simply outset producer thread yesteryear commenting consumer.start(); If consumer thread is non running too thus producer volition block at queue.put(event); call, too y'all won't see [PRODUCER] published lawsuit : FOUR.

This happens because of particular conduct of SynchronousQueue, which guarantees that the thread inserting information volition block until in that place is a thread to take away that information or vice-versa. You tin seek out the other role of code yesteryear commenting producer.start(); and alone starting consumer thread.

import java.util.concurrent.SynchronousQueue;  /**  * Java Program to solve Producer Consumer work using SynchronousQueue. H5N1  * telephone band to put() volition block until in that place is a corresponding thread to take() that  * element.  *  * @author Javin Paul  */ public class SynchronousQueueDemo{      public static void main(String args[]) {          final SynchronousQueue<String> queue = new SynchronousQueue<String>();          Thread producer = new Thread("PRODUCER") {             public void run() {                 String lawsuit = "FOUR";                 try {                     queue.put(event); // thread volition block here                     System.out.printf("[%s] published lawsuit : %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 lawsuit = queue.take(); // thread volition block here                     System.out.printf("[%s] consumed lawsuit : %s %n", Thread                             .currentThread().getName(), event);                 } catch (InterruptedException e) {                     e.printStackTrace();                 }              }         };          consumer.start(); // starting consumer thread      }  }  Output: [CONSUMER] consumed lawsuit : FOUR  [PRODUCER] published lawsuit : FOUR 

If y'all possess got mail the output carefully too thus y'all would possess got noticed that gild of events are reversed. Seems [CONSUMER] thread is consuming information fifty-fifty before [PRODUCER] thread has produced it. This happens because yesteryear default SynchronousQueue doesn't guarantee whatsoever order, but it has a fairness policy, which if laid to truthful allows access to threads inwards FIFO order. You tin enable this fairness policy yesteryear passing truthful to overloaded constructor of SynchronousQueue i.e. new SynchronousQueue(boolean fair).



Things to recollect close SynchronousQueue inwards Java

Here are about of the of import properties of this particular blocking queue inwards Java. It's rattling useful to transfer information from i thread to about other thread synchronously. It doesn't possess got whatsoever capacity too blocks until in that place is a thread on the other end.

1) SynchronousQueue blocks until about other thread is laid upwardly to possess got the element, i thread is trying to put.

2) SynchronousQueue has null capacity.

3) SynchronousQueue is used to implement queuing strategy of  direct hand-off, where thread hands-off to waiting thread, else creates novel i if allowed, else business rejected.

4) This queue does non permit null elements, adding null elements volition effect inwards NullPointerException.

5) For purposes of other Collection methods (for instance contains), a SynchronousQueue acts every bit an empty collection.

6) You cannot peek at a synchronous queue because an chemical constituent is alone acquaint when y'all endeavour to take away it; Similarly y'all cannot insert an chemical constituent (using whatsoever method) unless about other thread is trying to take away it.

7) You cannot iterate over SynchronousQueue as in that place is nil to iterate.

8) H5N1 SynchronousQueue constructed amongst fairness policy laid to truthful grants threads access inwards FIFO order.

That's all close SynchronousQueue inwards Java. We possess got seen about particular belongings of this particular concurrent collection, too learned how to solve classical producer consumer work using SynchronousQueue inwards Java.  By the agency calling it a Queue is chip confusing because it doesn't possess got whatsoever capacity to concur your element. Call to put() functioning volition non consummate until in that place is a thread which is calling take() operation. It's meliorate endure a rendezvous betoken betwixt threads to part objects. In other words, its a utility to synchronously part information betwixt 2 threads inwards Java, in all probability a safer alternative of wait too notify methods.

Further Learning
Multithreading too Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
Applying Concurrency too Multi-threading to Common Java Patterns
Java Concurrency inwards Practice Course yesteryear Heinz Kabutz


0 Response to "Synchronousqueue Illustration Inward Coffee - Produer Consumer Solution"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel