producer consumer design pattern with blocking queue example in java.pdf

Upload: gaurav-pawar

Post on 02-Jun-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 Producer Consumer Design Pattern with Blocking Queue Example in Java.pdf

    1/7

    Queue in Java Java The Java Class Java Wait For

    Posts

    Comments

  • 8/10/2019 Producer Consumer Design Pattern with Blocking Queue Example in Java.pdf

    2/7

    Design Pattern for Java

    Synchronized This Java

    What Is Class in Java

  • 8/10/2019 Producer Consumer Design Pattern with Blocking Queue Example in Java.pdf

    3/7

    9/23/2014 Producer Consumer Design Pattern with Blocking Queue Example in Java

    http://javarevisited.blogspot.sg/2012/02/producer-consumer-design-pattern-with.html 3/7

    When to use Thread or Runnable interface in Java?

    What does Volatile keyword do in Java

    How to Stop Thread in Java

    How to prevent deadlock in Java Code

    How to implement Thread in Java

    How to deal with blocking method in Java

    How to use Factory Design pattern in Java

    Recommended by

    Posted by Javin Paul at 5:44 AM

    Labels: core java , core java interview question

    Location: United States

    8 comments :

    Anonymous said...

    Recently I got this question in interview with different scenario. How to resolve the producer and consumer

    problem so that my CPU cycle can be used to 100%. For ex if producer is producing less and consumer is consuming

    fast then your CPU cycle is getting wasted which is associated with cost. So what would be strategy to resolve this.

    Any suggestion?

    March 5, 2013 at 12:15 PM

    Mudit Srivastava said...

    Well i see something is missing, how to define the size of queue ?

    March 7, 2013 at 9:06 AM

    SARAL SAXENA said...

    Hi Javin, ..gr8 article few things that I want to add in this is...

    BlockingQueue Code Example

    Here is an example of how to use a BlockingQueue. The example uses the ArrayBlockingQueue implementation of

    the BlockingQueue interface.

    First, the BlockingQueueExample class which starts a Producer and a Consumer in separate threads. The Producer

    inserts strings into a shared BlockingQueue, and the Consumer takes them out.

    public class BlockingQueueExample {

    public static void main(String[] args) throws Exception {

    BlockingQueue queue = new ArrayBlockingQueue(1024);

    Producer producer = new Producer(queue);

    Consumer consumer = new Consumer(queue);

    new Thread(producer).start();

    new Thread(consumer).start();

    Thread.sleep(4000);

    }

    }

    Here is the Producer class. Notice how it sleeps a second between each put() call. This will cause the Consumer to

    block, while waiting for objects in the queue.

    public class Producer implements Runnable{

    protected BlockingQueue queue = null;

    public Producer(BlockingQueue queue) {

    this.queue = queue;

    }

    public void run() {

    try {

    queue.put("1");

    Thread.sleep(1000);

    queue.put("2");

    What is Race Condition in multithreading 2

    Examp...

    JSTL Set tag examples or in JSP Java

    J2E...

    Difference between throw and throws in

    Exception h...

    Difference between LinkedList vs ArrayList in

    Java...

    How to encode decode String in Java base64

    Encodin...

    Producer Consumer Design Pattern with Blocking

    Que...

    Why non-static variable cannot be referenced

    from ...

    fail-safe vs fail-fast Iterator in Java

    How to fix java.lang.ClassNotFoundException:

    org.a...

    What is blocking methods in Java and how do

    deal w...

    Why wait, notify and notifyAll is defined in

    Objec...

    3 Example to Compare two Dates in Java

    Difference between instance class and local

    variab...

    January ( 35 )

    2011 ( 145 )

    2010 ( 33 )

    References

    Java API documentation JDK 6

    Spring framework doc

    Struts

    JDK 7 API

    MySQL

    Linux

    Eclipse

    jQuery

    Copyright by Javin Paul 2012. Powered by Blogger.

    Save on Double Zoom Kitedge.canon.co.in/EOS1200D

    Say EOS 1200D & save INR 12995* on Double Zoom Kit. Get Free* gifts

    You might like:

    Why wait, notify and notifyAll is defined in Object Class and not on Thread class in Java

    20 Things on Synchronization, Synchroinzed Block, Method, locking and Threadsafety in Java

    How to Join Multiple Threads in Java - Thread Join Example

    ReentrantLock Example in Java, Difference between synchronized vs ReentrantLock

    +55 Recommend this on Google

    Searching for professional web design?

    http://www.blogger.com/share-post.g?blogID=8712770457197348465&postID=8379818278416374862&target=facebookhttp://www.blogger.com/share-post.g?blogID=8712770457197348465&postID=8379818278416374862&target=twitterhttp://www.blogger.com/share-post.g?blogID=8712770457197348465&postID=8379818278416374862&target=bloghttp://www.blogger.com/share-post.g?blogID=8712770457197348465&postID=8379818278416374862&target=emailhttp://googleads.g.doubleclick.net/aclk?sa=L&ai=CZ2mLHm0gVJO8EZCbuATIvYGICaXVqdYF9ZGVnqYBwI23ARABIJ_C4BpQsfO-jgJg5crlg7QOyAEBqQLzVbqu0aNRPqgDAcgDwwSqBL8BT9CViKG6Bvfygxm2GT_2NEbRb4eHEvrwDnagep5OB06xA4S7ubK7YANVmTKA8gOlnSiraSCn64cx37k_djinvPnF6u08pdZKQPHmYMdQxEFRJqkvBDUUPWwQ65IbhEvnsb_DdplKkRANviTGm-PF4tAtd9S1k1u-JSB8yQIG5JOStQ6uWXmaXTp41b6MudL60bQANaPWeIeFQClYe8JkDTThRfSTp3ZQrmiTqm8cE9zin9OwZdYVHOlYWs0iZkaAB-2TjjA&num=1&sig=AOD64_0qQLH1MdgpLmNCiOLiMdP_ulcjJA&client=ca-pub-5808379456926196&adurl=http://edge.canon.co.in/eos1200d/%3Futm_source%3Dgoogle%26utm_medium%3Dcpc%26utm_content%3DText_Ads%26utm_campaign%3DSayEOS1200Dhttp://googleads.g.doubleclick.net/aclk?sa=L&ai=CZ2mLHm0gVJO8EZCbuATIvYGICaXVqdYF9ZGVnqYBwI23ARABIJ_C4BpQsfO-jgJg5crlg7QOyAEBqQLzVbqu0aNRPqgDAcgDwwSqBL8BT9CViKG6Bvfygxm2GT_2NEbRb4eHEvrwDnagep5OB06xA4S7ubK7YANVmTKA8gOlnSiraSCn64cx37k_djinvPnF6u08pdZKQPHmYMdQxEFRJqkvBDUUPWwQ65IbhEvnsb_DdplKkRANviTGm-PF4tAtd9S1k1u-JSB8yQIG5JOStQ6uWXmaXTp41b6MudL60bQANaPWeIeFQClYe8JkDTThRfSTp3ZQrmiTqm8cE9zin9OwZdYVHOlYWs0iZkaAB-2TjjA&num=1&sig=AOD64_0qQLH1MdgpLmNCiOLiMdP_ulcjJA&client=ca-pub-5808379456926196&adurl=http://edge.canon.co.in/eos1200d/%3Futm_source%3Dgoogle%26utm_medium%3Dcpc%26utm_content%3DText_Ads%26utm_campaign%3DSayEOS1200Dhttp://googleads.g.doubleclick.net/aclk?sa=L&ai=CZ2mLHm0gVJO8EZCbuATIvYGICaXVqdYF9ZGVnqYBwI23ARABIJ_C4BpQsfO-jgJg5crlg7QOyAEBqQLzVbqu0aNRPqgDAcgDwwSqBL8BT9CViKG6Bvfygxm2GT_2NEbRb4eHEvrwDnagep5OB06xA4S7ubK7YANVmTKA8gOlnSiraSCn64cx37k_djinvPnF6u08pdZKQPHmYMdQxEFRJqkvBDUUPWwQ65IbhEvnsb_DdplKkRANviTGm-PF4tAtd9S1k1u-JSB8yQIG5JOStQ6uWXmaXTp41b6MudL60bQANaPWeIeFQClYe8JkDTThRfSTp3ZQrmiTqm8cE9zin9OwZdYVHOlYWs0iZkaAB-2TjjA&num=1&sig=AOD64_0qQLH1MdgpLmNCiOLiMdP_ulcjJA&client=ca-pub-5808379456926196&adurl=http://edge.canon.co.in/eos1200d/%3Futm_source%3Dgoogle%26utm_medium%3Dcpc%26utm_content%3DText_Ads%26utm_campaign%3DSayEOS1200Dhttp://googleads.g.doubleclick.net/aclk?sa=L&ai=CZ2mLHm0gVJO8EZCbuATIvYGICaXVqdYF9ZGVnqYBwI23ARABIJ_C4BpQsfO-jgJg5crlg7QOyAEBqQLzVbqu0aNRPqgDAcgDwwSqBL8BT9CViKG6Bvfygxm2GT_2NEbRb4eHEvrwDnagep5OB06xA4S7ubK7YANVmTKA8gOlnSiraSCn64cx37k_djinvPnF6u08pdZKQPHmYMdQxEFRJqkvBDUUPWwQ65IbhEvnsb_DdplKkRANviTGm-PF4tAtd9S1k1u-JSB8yQIG5JOStQ6uWXmaXTp41b6MudL60bQANaPWeIeFQClYe8JkDTThRfSTp3ZQrmiTqm8cE9zin9OwZdYVHOlYWs0iZkaAB-2TjjA&num=1&sig=AOD64_0qQLH1MdgpLmNCiOLiMdP_ulcjJA&client=ca-pub-5808379456926196&adurl=http://edge.canon.co.in/eos1200d/%3Futm_source%3Dgoogle%26utm_medium%3Dcpc%26utm_content%3DText_Ads%26utm_campaign%3DSayEOS1200Dhttp://void%280%29/http://void%280%29/http://void%280%29/http://javarevisited.blogspot.com/2011/12/factory-design-pattern-java-example.htmlhttp://www.blogger.com/How%20to%20implement%20Thread%20in%20Javahttp://javarevisited.blogspot.com/2011/02/how-to-implement-thread-in-java.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-deadlock-in-java-how-to-fix-it.htmlhttp://javarevisited.blogspot.com/2011/10/how-to-stop-thread-java-example.htmlhttp://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.htmlhttp://javarevisited.blogspot.com/2012/01/difference-thread-vs-runnable-interface.htmlhttp://www.addthis.com/bookmark.php?v=250&pubid=javabuddyhttp://www.addthis.com/bookmark.php?v=300&winname=addthis&pub=javabuddy&source=tbx32-300&lng=en-US&s=hackernews&url=http%3A%2F%2Fjavarevisited.blogspot.com%2F2012%2F02%2Fproducer-consumer-design-pattern-with.html&title=Producer%20Consumer%20Design%20Pattern%20with%20Blocking%20Queue%20Example%20in%20Java&ate=AT-javabuddy/-/-/54206d1b8c504883/8&frommenu=1&uid=54206d1b31e1a1be&ct=1&pre=http%3A%2F%2Fjava67.blogspot.in%2F2012%2F10%2Fjava-interview-questions-for-2-to-3-4-years-experienced.html&tt=0&captcha_provider=nucaptchahttp://www.addthis.com/bookmark.php?v=300&winname=addthis&pub=javabuddy&source=tbx32-300&lng=en-US&s=dzone&url=http%3A%2F%2Fjavarevisited.blogspot.com%2F2012%2F02%2Fproducer-consumer-design-pattern-with.html&title=Producer%20Consumer%20Design%20Pattern%20with%20Blocking%20Queue%20Example%20in%20Java&ate=AT-javabuddy/-/-/54206d1b8c504883/7&frommenu=1&uid=54206d1b6c618783&ct=1&pre=http%3A%2F%2Fjava67.blogspot.in%2F2012%2F10%2Fjava-interview-questions-for-2-to-3-4-years-experienced.html&tt=0&captcha_provider=nucaptchahttp://www.addthis.com/bookmark.php?v=300&winname=addthis&pub=javabuddy&source=tbx32-300&lng=en-US&s=digg&url=http%3A%2F%2Fjavarevisited.blogspot.com%2F2012%2F02%2Fproducer-consumer-design-pattern-with.html&title=Producer%20Consumer%20Design%20Pattern%20with%20Blocking%20Queue%20Example%20in%20Java&ate=AT-javabuddy/-/-/54206d1b8c504883/6&frommenu=1&uid=54206d1bd078a4e3&ct=1&pre=http%3A%2F%2Fjava67.blogspot.in%2F2012%2F10%2Fjava-interview-questions-for-2-to-3-4-years-experienced.html&tt=0&captcha_provider=nucaptchahttp://www.addthis.com/bookmark.php?v=300&winname=addthis&pub=javabuddy&source=tbx32-300&lng=en-US&s=reddit&url=http%3A%2F%2Fjavarevisited.blogspot.com%2F2012%2F02%2Fproducer-consumer-design-pattern-with.html&title=Producer%20Consumer%20Design%20Pattern%20with%20Blocking%20Queue%20Example%20in%20Java&ate=AT-javabuddy/-/-/54206d1b8c504883/5&frommenu=1&uid=54206d1b8b8f6073&ct=1&pre=http%3A%2F%2Fjava67.blogspot.in%2F2012%2F10%2Fjava-interview-questions-for-2-to-3-4-years-experienced.html&tt=0&captcha_provider=nucaptchahttp://www.addthis.com/bookmark.php?v=300&winname=addthis&pub=javabuddy&source=tbx32-300&lng=en-US&s=stumbleupon&url=http%3A%2F%2Fjavarevisited.blogspot.com%2F2012%2F02%2Fproducer-consumer-design-pattern-with.html&title=Producer%20Consumer%20Design%20Pattern%20with%20Blocking%20Queue%20Example%20in%20Java&ate=AT-javabuddy/-/-/54206d1b8c504883/4&frommenu=1&uid=54206d1bfc15b452&ct=1&pre=http%3A%2F%2Fjava67.blogspot.in%2F2012%2F10%2Fjava-interview-questions-for-2-to-3-4-years-experienced.html&tt=0&captcha_provider=nucaptchahttp://www.addthis.com/bookmark.php?v=300&winname=addthis&pub=javabuddy&source=tbx32-300&lng=en-US&s=linkedin&url=http%3A%2F%2Fjavarevisited.blogspot.com%2F2012%2F02%2Fproducer-consumer-design-pattern-with.html&title=Producer%20Consumer%20Design%20Pattern%20with%20Blocking%20Queue%20Example%20in%20Java&ate=AT-javabuddy/-/-/54206d1b8c504883/3&frommenu=1&uid=54206d1bbcab84a2&ct=1&pre=http%3A%2F%2Fjava67.blogspot.in%2F2012%2F10%2Fjava-interview-questions-for-2-to-3-4-years-experienced.html&tt=0&captcha_provider=nucaptchahttp://www.addthis.com/bookmark.php?v=300&winname=addthis&pub=javabuddy&source=tbx32-300&lng=en-US&s=delicious&url=http%3A%2F%2Fjavarevisited.blogspot.com%2F2012%2F02%2Fproducer-consumer-design-pattern-with.html&title=Producer%20Consumer%20Design%20Pattern%20with%20Blocking%20Queue%20Example%20in%20Java&ate=AT-javabuddy/-/-/54206d1b8c504883/2&frommenu=1&uid=54206d1b419a5153&ct=1&pre=http%3A%2F%2Fjava67.blogspot.in%2F2012%2F10%2Fjava-interview-questions-for-2-to-3-4-years-experienced.html&tt=0&captcha_provider=nucaptcha
  • 8/10/2019 Producer Consumer Design Pattern with Blocking Queue Example in Java.pdf

    4/7

    9/23/2014 Producer Consumer Design Pattern with Blocking Queue Example in Java

    http://javarevisited.blogspot.sg/2012/02/producer-consumer-design-pattern-with.html 4/7

    Thread.sleep(1000);

    queue.put("3");

    } catch (InterruptedException e) {

    e.printStackTrace();

    }

    }

    }

    Here is the Consumer class. It just takes out the objects from the queue, and prints them to System.out.

    public class Consumer implements Runnable{

    protected BlockingQueue queue = null;

    public Consumer(BlockingQueue queue) {

    this.queue = queue;

    }

    public void run() {

    try {

    System.out.println(queue.take());

    System.out.println(queue.take());

    System.out.println(queue.take());

    } catch (InterruptedException e) {

    e.printStackTrace();

    }

    }

    }

    April 13, 2013 at 9:26 PM

    yyc said...

    The above example is good but too simple. Would you minding providing a example with multiple producers and

    consumers and stopping the program once producers have done their jobs?

    October 8, 2013 at 8:30 PM

    Anonymous said...

    I tried out following implementation of Producer-Consumer and it doesn't list out all the elements from the list.

    Few of them are missing.

    I wanted to have one producer & multiple consumers and have the consumers take data out of the list in round

    robin fashion, but not working as expected. Would you be able to point me out the error in the code? Thanks.

    public class ProdConController {

    public static void main(String[] args) throws Exception {

    List stringList = new ArrayList();

    SignalObject signalObject = new SignalObject();

    ProdWorker prodWorker = new ProdWorker(stringList, signalObject);

    ConWorker conWorker1 = new ConWorker(stringList, signalObject, "worker1");

    ConWorker conWorker2 = new ConWorker(stringList, signalObject, "worker2");

    Thread prodThrd = new Thread(prodWorker);

    Thread conThrd1 = new Thread(conWorker1);

    Thread conThrd2 = new Thread(conWorker2);

    prodThrd.start();

    conThrd1.start();

    conThrd2.start();

    prodThrd.join();

    conThrd1.join();

    conThrd2.join();

    }

    }

    public class SignalObject {

    private boolean isDataAvailable = false;

    public synchronized boolean isDataAvailable() {

    return isDataAvailable;

    }

    public synchronized void setDataAvailable(boolean dataAvailable) {

    isDataAvailable = dataAvailable;

    }

    }

    public class ProdWorker implements Runnable {

    private List stringList;

    private SignalObject signalObject;

    public ProdWorker(List stringList, SignalObject signalObject) {

    this.stringList = stringList;

    this.signalObject = signalObject;

    }

    @Override

    public void run() {

  • 8/10/2019 Producer Consumer Design Pattern with Blocking Queue Example in Java.pdf

    5/7

    9/23/2014 Producer Consumer Design Pattern with Blocking Queue Example in Java

    http://javarevisited.blogspot.sg/2012/02/producer-consumer-design-pattern-with.html 5/7

    for (int i = 1; i = max CPU threads (cores / hyper threads) While consumers are

    waiting, producers will allocate all CPU resources and vice versa. Also the queue size >= max CPU threads.

    December 1, 2013 at 1:26 AM

    Anonymous said...

    Can you please share solution of Producer Consumer problem using Semaphore? I know it can be solved using

    multiple way including BlockingQueue, wait and notify as shown above, but I am really interested in using

    Semaphore. Thanks

    February 13, 2014 at 9:51 PM

    sathish said...

    package Thread;

    import java.util.concurrent.Semaphore;

    class SharedResource

    {

  • 8/10/2019 Producer Consumer Design Pattern with Blocking Queue Example in Java.pdf

    6/7

    9/23/2014 Producer Consumer Design Pattern with Blocking Queue Example in Java

    http://javarevisited.blogspot.sg/2012/02/producer-consumer-design-pattern-with.html 6/7

    int n;

    static Semaphore semCons = new Semaphore(0);

    static Semaphore semProd = new Semaphore(1);

    void put(int n)

    {

    try {

    semProd.acquire();

    } catch (InterruptedException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    this.n=n;

    System.out.println("Put : " + n);

    semCons.release();

    }

    void get()

    {

    try {

    semCons.acquire();

    } catch (InterruptedException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    System.out.println("Got : "+n);

    semProd.release();

    }

    }

    class Consumer implements Runnable

    {

    SharedResource sr;

    public Consumer(SharedResource sr)

    {

    this.sr = sr;

    new Thread(this, "Consumer").start();

    }

    @Override

    public void run()

    {

    for(int i=0;i

  • 8/10/2019 Producer Consumer Design Pattern with Blocking Queue Example in Java.pdf

    7/7

    9/23/2014 Producer Consumer Design Pattern with Blocking Queue Example in Java

    http://javarevisited.blogspot.sg/2012/02/producer-consumer-design-pattern-with.html 7/7

    About Me Privacy Policy

    Newer Post Older Post

    Enter your comment...

    Comment as: Google Accou

    Publish

    Preview

    Home

    Subscribe to: Post Comments ( Atom )