Producer Consumer Blueprint Pattern Amongst Blocking Queue Representative Inwards Java

Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces coupling between
Producer in addition to Consumer past times separating Identification of piece of work amongst Execution of Work. In producer consumer blueprint pattern a shared queue is used to command the menstruation in addition to this separation allows you lot to code producer in addition to consumer separately. It likewise addresses the number of unlike timing require to hit special or consuming item. past times using producer consumer pattern both Producer in addition to Consumer Thread tin piece of work amongst unlike speed. In this article nosotros volition run across What is producer consumer problem which is real popular multi-threading interview question, How to solve producer consumer work using Blocking Queue in addition to Benefits of using Producer Consumer blueprint pattern.

 

Real World Example of Producer Consumer Design Pattern

 is a classic concurrency or threading pattern which reduces coupling betwixt Producer Consumer Design Pattern amongst Blocking Queue Example inwards JavaProducer consumer pattern is every where inwards existent life in addition to describe coordination in addition to collaboration. Like one person is preparing nutrient (Producer) spell other i is serving nutrient (Consumer), both volition utilization shared table for putting nutrient plates in addition to taking nutrient plates. Producer which is the mortal preparing nutrient volition await if table is total in addition to Consumer (Person who is serving food) volition await if tabular array is empty. tabular array is a shared object here. On Java library Executor framework itself implement Producer Consumer blueprint pattern travel separating responsibility of add-on in addition to execution of task.



Benefit of Producer Consumer Pattern

Its indeed a useful design pattern in addition to used most usually spell writing multi-threaded or concurrent code. here
is few of its benefit:

1) Producer Consumer Pattern elementary development. you lot tin Code Producer in addition to Consumer independently in addition to Concurrently, they only demand to know shared object.

2) Producer doesn't demand to know almost who is consumer or how many consumers are there. Same is truthful amongst Consumer.

3) Producer in addition to Consumer tin piece of work amongst unlike speed. There is no opportunity of Consumer consuming half-baked item.
In fact past times monitoring consumer speed i tin innovate to a greater extent than consumer for ameliorate utilization.

4) Separating producer in addition to Consumer functionality consequence inwards to a greater extent than clean, readable in addition to manageable code.
 

Producer Consumer Problem inwards Multi-threading

Producer-Consumer Problem is also a popular coffee interview question where interviewer enquire to implement producer consumer blueprint pattern in addition to thus that Producer should await if Queue or bucket is total in addition to Consumer should await if queue or
bucket is empty. This work tin travel implemented or solved past times unlike ways inwards Java, classical agency is using wait in addition to notify method to communicate betwixt Producer in addition to Consumer thread in addition to blocking each of them on private status similar total queue in addition to empty queue. With introduction of BlockingQueue Data Structure inwards Java 5 Its at i time much simpler because BlockingQueue provides this command implicitly past times introducing blocking methods put() in addition to take(). Now you lot don't require to utilization await in addition to notify to communicate betwixt Producer in addition to Consumer. BlockingQueue put() method volition block if Queue is total inwards instance of Bounded Queue in addition to take() volition block if Queue is empty. In side past times side department nosotros volition run across a code instance of Producer Consumer blueprint pattern.
 

Using Blocking Queue to implement Producer Consumer Pattern

BlockingQueue amazingly simplifies implementation of Producer-Consumer blueprint pattern past times providing outofbox back upwards of blocking on put() in addition to take(). Developer doesn't demand to write confusing in addition to critical slice of wait-notify code to implement communication. BlockingQuue is an interface in addition to Java five provides unlike implantation similar ArrayBlockingQueue in addition to LinkedBlockingQueue , both implement FIFO social club or elements, spell ArrayLinkedQueue is bounded inwards nature LinkedBlockingQueue is optionally bounded. hither is a consummate code instance of Producer Consumer pattern amongst BlockingQueue. Compare it amongst classic wait notify code, its much simpler in addition to slow to understand.

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

public cast ProducerConsumerPattern {

    world static void main(String args[]){
  
     //Creating shared object
     BlockingQueue sharedQueue = novel LinkedBlockingQueue();
 
     //Creating Producer in addition to Consumer Thread
     Thread prodThread = novel Thread(new Producer(sharedQueue));
     Thread consThread = novel Thread(new Consumer(sharedQueue));

     //Starting producer in addition to Consumer thread
     prodThread.start();
     consThread.start();
    }
 
}

//Producer Class inwards java
class Producer implements Runnable {

    private finally BlockingQueue sharedQueue;

    world Producer(BlockingQueue sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    @Override
    world void run() {
        for(int i=0; i<10; i++){
            sweat {
                System.out.println("Produced: " + i);
                sharedQueue.put(i);
            } select handgrip of (InterruptedException ex) {
                Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}

//Consumer Class inwards Java
class Consumer implements Runnable{

    private finally BlockingQueue sharedQueue;

    world Consumer (BlockingQueue sharedQueue) {
        this.sharedQueue = sharedQueue;
    }
  
    @Override
    world void run() {
        while(true){
            sweat {
                System.out.println("Consumed: "+ sharedQueue.take());
            } select handgrip of (InterruptedException ex) {
                Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
  
  
}

Output:
Produced: 0
Produced: 1
Consumed: 0
Produced: 2
Consumed: 1
Produced: 3
Consumed: 2
Produced: 4
Consumed: 3
Produced: 5
Consumed: 4
Produced: 6
Consumed: 5
Produced: 7
Consumed: 6
Produced: 8
Consumed: 7
Produced: 9
Consumed: 8
Consumed: 9

You run across Producer Thread  produced number in addition to Consumer thread consumes it inwards FIFO social club because blocking queue allows elements to travel accessed inwards FIFO.

That’s all on How to utilization Blocking Queue to solve Producer Consumer problem or example of Producer consumer blueprint pattern. I am certain its much ameliorate than await notify instance but travel cook amongst both if you lot are going for whatsoever Java Interview every bit Interview may enquire you lot both way.

Further Learning
Multithreading in addition to Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
When to utilization Thread or Runnable interface inwards Java?

Komentar

Postingan populer dari blog ini

Fixing Java.Net.Bindexception: Cannot Assign Requested Address: Jvm_Bind Inwards Tomcat, Jetty

5 Deviation Betwixt Constructor In Addition To Static Mill Method Inward Java- Pros In Addition To Cons

Top V Websites For Practicing Information Structures Together With Algorithms For Coding Interviews Free