Wednesday, 16 September 2015

Blocking Queue (Typical Example of Producer and Consumer )

Some days ago my boss comes with new changes in our product. Then I started looking into solution that solve my problem.
I will explain my problem and its solution (Typical producer, consumer problem).

we have three objects 

  1. Learning Module
  2. Validate 
  3. Training Content
Relations 
  • Learning Module one To Many Validate 
  • Learning Module one To Many Training Content

So, typical case is that we have Learning Module with around 20,000 validate object connected to it. Whenever new Training Content connected to Learning Module we have to update all Validate object(20000) connect to Learning Module. 
First thing that comes in mind is put process of updating Validate Object in separate thread. Ok and that is the solution, punting it in separate thread.

Problem with above solution is we don't to create new thread for every time new Training Content connected to Learning Module.(Lets 1000 user connecting Training Content to different Learning Module then 1000 thread is going created .... and bang).

So, We comes with idea that we dedicate one single thread for all Learning Module connecting to New Training Content for updating connected Validate Object.
In this we have multiple producer (Action of connection Learning Module and Training Content) and one consumer thread (For Update related validate object).       
From above we have multiple user that connecting Learning Module and updating of related Validate object is done by single dedicated thread.
As form java 1.5 we have some concurrent API that helps to build typical producer consumer problem and found BlockingQueue.

Blocking Queue is block consumer thread if it is empty and Block producer if it is overflow.We don't have to build Wait/Notify event for thread handling things.