Skip to main content

Posts

Producer Consumer Design Pattern By using wait(), notify() and notifyAll() methods

Producer Consumer Problem is a classical concurrency problem. In fact it is one of the concurrency design pattern .   Producer Consumer Design Patter can either be implemented using following two approaces. By using wait(), notify() and notifyAll() methods By using BlockingQueue  In this post I will explain implementation using wait() and notify() method. If you are interested in the implementation using Blocking Queue, you can check my post  Producer Consumer Design Pattern using BlockingQueue . The Object class in java contains three final methods that allows threads to communicate about the lock status of a resource. These methods are wait() , notify() and notifyAll() .  We can use  wait() method to pause execution of thread. notify() and notifyAll() methods are used to wake up waiting th...

BlockingQueue for producer and consumer problem

How BlockingQueue fit into Solution Any effective solution of producer consumer problem has to control the invocation of produce’s put() method which generates the resource – and consumer’s take() method which consumes the resource. Once you achieve this control of blocking the methods, you have solved the problem. Java provides out of the box support to control such method invocations where one thread is creating resources and other is consuming them- through  BlockingQueue . The Java  BlockingQueue  interface in the  java.util.concurrent  package represents a queue which is thread safe to put into, and take instances from. BlockingQueue is a construct where one thread putting resources into it, and another thread taking from it. This is exactly what is needed to solve the producer consumer problem. Let’s solve the problem now !! Using BlockingQueue to solve Producer Consumer problem Producer Below code is for producer thread. class ...