Producer Consumer Solution using BlockingQueue inwards Java

Producer Consumer job is ane of the classic multi-threading problems inward figurer scientific discipline in addition to the multi-threading world. It's tricky because it involves inter-thread communication, simply it's of import because most of the multi-threading problems fits into this category. There are many ways to solve producer consumer job inward Java e.g. y'all tin give the axe solve this yesteryear using wait() in addition to notify() method, equally discussed here, or y'all tin give the axe work the Semaphore to solve this problem. In this article, y'all volition larn a 3rd way to solve the producer-consumer job yesteryear using the BlockingQueue inward Java. It is arguably the simplest way to solve this job inward whatever programming linguistic communication because blocking queue information construction non solely provides storage simply also provides menses command in addition to thread-safety, which makes the code actually simple. Brian Goetz has also explained this telephone substitution shape in addition to designing inward his classic Java Concurrency inward Practice book, a must read for serious Java developers.



Producer Consumer Pattern using BlockingQueue

Java provides a built-in blocking queue information construction inward java.util.concurrent package. It was added on JDK amongst multiple concurrent utilities e.g. CountDownLatch, CyclicBarrier, in addition to Callable in addition to Future classes.

The java.util.concurrent.BlockingQueue is an interface in addition to comes amongst 2 ready-made implementations in addition to thence ArrayLinkedBlockingQueue in addition to LinkedBlockingQueue. As the cite suggests, ane is backed yesteryear an array acre other is backed yesteryear linked list.


In gild to solve the producer-consumer problem, nosotros volition create 2 threads which volition copy producer in addition to consumer in addition to instead of shared object nosotros volition work the shared BlockingQueue. Our code volition live on simple, the producer will add together an chemical constituent into queue in addition to consumer volition take away the element.

BlockingQueue provides a put() method to shop the chemical constituent in addition to take() method to recall the element. Both are blocking method, which way put() volition block if the queue has reached its capacity in addition to at that topographic point is no house to add together a novel element. Similarly, take() method volition block if blocking queue is empty. So, y'all tin give the axe run into that critical requirement of the producer-consumer designing is met correct there, y'all don't take to pose whatever thread synchronization code.

 Producer Consumer job is ane of the classic multi Producer Consumer Solution using BlockingQueue inward Java


Producer-Consumer Example inward Java using BlockingQueue

Here is our sample Java computer program to solve the classical producer consumer job using BlockingQueue inward Java:
import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue;  /**  * Producer Consumer Problem solution using BlockingQueue inward Java.  * BlockingQueue non solely render a information construction to shop information  * simply also gives y'all menses control, require for inter thread communication.  *   * @author Javin Paul  */ public class ProducerConsumerSolution {      public static void main(String[] args) {         BlockingQueue<Integer> sharedQ = new LinkedBlockingQueue<Integer>();                  Producer p = new Producer(sharedQ);         Consumer c = new Consumer(sharedQ);                  p.start();         c.start();     } }  class Producer extends Thread {     private BlockingQueue<Integer> sharedQueue;      public Producer(BlockingQueue<Integer> aQueue) {         super("PRODUCER");         this.sharedQueue = aQueue;     }      public void run() {         // no synchronization needed         for (int i = 0; i < 10; i++) {             try {                 System.out.println(getName() + " produced " + i);                 sharedQueue.put(i);                 Thread.sleep(200);             } catch (InterruptedException e) {                 e.printStackTrace();             }          }     } }  class Consumer extends Thread {     private BlockingQueue<Integer> sharedQueue;      public Consumer(BlockingQueue<Integer> aQueue) {         super("CONSUMER");         this.sharedQueue = aQueue;     }      public void run() {         try {             while (true) {                 Integer special = sharedQueue.take();                 System.out.println(getName() + " consumed " + item);             }         } catch (InterruptedException e) {             e.printStackTrace();         }     } }  Output PRODUCER produced 0 CONSUMER consumed 0 PRODUCER produced 1 CONSUMER consumed 1 PRODUCER produced 2 CONSUMER consumed 2 PRODUCER produced 3 CONSUMER consumed 3 PRODUCER produced 4 CONSUMER consumed 4 PRODUCER produced 5 CONSUMER consumed 5 PRODUCER produced 6 CONSUMER consumed 6 PRODUCER produced 7 CONSUMER consumed 7 PRODUCER produced 8 CONSUMER consumed 8 PRODUCER produced 9 CONSUMER consumed 9


Explanation of code
If y'all await at to a higher house code example, y'all volition notice that nosotros receive got created in addition to started 2 threads in addition to named them Producer in addition to Consumer. The Producer thread executes the code within run() method, which adds 10 Integer object starting from 0.

After adding each element, the Producer thread is sleeping for 200 milliseconds yesteryear calling Thread.sleep() method. This gives fourth dimension to the Consumer thread to swallow elements from Queue, that's why our code never blocks.

You tin give the axe run into that our Producer in addition to Consumer threads are working inward sync because of Thread.sleep() nosotros receive got introduced later on put() call. You tin give the axe farther experiment amongst the code yesteryear removing the code to pause the Producer thread or inserting intermission on Consumer thread to  create scenarios where Queue is total or empty.


Benefits of using BlockingQueue to solve Producer Consumer
  • Simple code, much to a greater extent than readable
  • less fault prone equally y'all don't receive got to bargain amongst whatever external synchronization

That's all close how to solve producer consumer job using BlockingQueue inward Java. In production code, y'all should ever work BlockingQueue, using wait() in addition to notify() is neither slow non desirable given y'all receive got amend tools available. Even Joshua Bloch's has advised inward Effective Java to prefer higher concurrency utilities in addition to libraries instead of writing your ain code. Remember, the code is solely written ane time simply read numerous fourth dimension for maintenance, troubleshooting in addition to back upwardly purpose.

Further Learning
Java Fundamentals: Collections
Applying Concurrency in addition to Multi-threading to Common Java Patterns
Grokking Algorithms yesteryear Aditya Bhargava
Java Programming Interview Exposed yesteryear Makham

If y'all similar this tutorial in addition to hungry to larn to a greater extent than close thread, synchronization, in addition to multi-threading in addition to thence cheque out next articles equally well:
  • Difference betwixt notify() in addition to notifyAll() inward Java? (answer)
  • The departure betwixt synchronized block in addition to methods inward Java? (answer)
  • The departure betwixt Callable in addition to Runnable inward Java? (answer)
  • Difference betwixt extends Thread vs implements Runnable inward Java? (answer)
  • When to work the volatile variable inward Java? (answer)

Subscribe to receive free email updates:

0 Response to "Producer Consumer Solution using BlockingQueue inwards Java"

Posting Komentar