Producer Consumer Pattern Pattern Alongside Blocking Queue Example Inwards Java
Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces coupling between
Producer in addition to Consumer yesteryear separating Identification of piece of work amongst Execution of Work. In producer consumer pattern pattern a shared queue is used to command the menses 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 attain exceptional or consuming item. yesteryear using producer consumer pattern both Producer in addition to Consumer Thread tin sack piece of work amongst unlike speed. In this article nosotros volition encounter 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 pattern pattern.
Real World Example of Producer Consumer Design Pattern
Producer consumer pattern is every where inwards existent life in addition to describe coordination in addition to collaboration. Like one person is preparing nutrient (Producer) piece other ane is serving nutrient (Consumer), both volition utilisation shared table for putting nutrient plates in addition to taking nutrient plates. Producer which is the soul preparing nutrient volition expect if table is total in addition to Consumer (Person who is serving food) volition expect if tabular array is empty. tabular array is a shared object here. On Java library Executor framework itself implement Producer Consumer pattern pattern hold upward 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 ordinarily piece writing multi-threaded or concurrent code. here
is few of its benefit:
1) Producer Consumer Pattern elementary development. you lot tin sack Code Producer in addition to Consumer independently in addition to Concurrently, they merely demand to know shared object.
2) Producer doesn't demand to know close who is consumer or how many consumers are there. Same is truthful amongst Consumer.
3) Producer in addition to Consumer tin sack piece of work amongst unlike speed. There is no direct chances of Consumer consuming half-baked item.
In fact yesteryear monitoring consumer speed ane tin sack innovate to a greater extent than consumer for amend utilization.
4) Separating producer in addition to Consumer functionality trial 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 pattern pattern in addition to thus that Producer should expect if Queue or bucket is total in addition to Consumer should expect if queue or
bucket is empty. This work tin sack hold upward implemented or solved yesteryear 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 directly much simpler because BlockingQueue provides this command implicitly yesteryear introducing blocking methods put() in addition to take(). Now you lot don't require to utilisation expect 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 adjacent department nosotros volition encounter a code instance of Producer Consumer pattern pattern.
Using Blocking Queue to implement Producer Consumer Pattern
BlockingQueue amazingly simplifies implementation of Producer-Consumer pattern pattern yesteryear providing outofbox back upward 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 v provides unlike implantation similar ArrayBlockingQueue in addition to LinkedBlockingQueue , both implement FIFO guild or elements, piece 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 tardily to understand.
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
public degree ProducerConsumerPattern {
populace 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 concluding BlockingQueue sharedQueue;
populace Producer(BlockingQueue sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
populace void run() {
for(int i=0; i<10; i++){
travail {
System.out.println("Produced: " + i);
sharedQueue.put(i);
} select handle of (InterruptedException ex) {
Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
//Consumer Class inwards Java
class Consumer implements Runnable{
private concluding BlockingQueue sharedQueue;
populace Consumer (BlockingQueue sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
populace void run() {
while(true){
travail {
System.out.println("Consumed: "+ sharedQueue.take());
} select handle 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 encounter Producer Thread produced number in addition to Consumer thread consumes it inwards FIFO guild because blocking queue allows elements to hold upward accessed inwards FIFO.
That’s all on How to utilisation Blocking Queue to solve Producer Consumer problem or example of Producer consumer pattern pattern. I am certain its much amend than expect notify instance but hold upward laid upward amongst both if you lot are going for whatever Java Interview equally 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 utilisation Thread or Runnable interface inwards Java?
0 Response to "Producer Consumer Pattern Pattern Alongside Blocking Queue Example Inwards Java"
Post a Comment