Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

download Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

of 13

Transcript of Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

  • 8/22/2019 Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

    1/13

    7/14/13 Producer Consumer Problem using Thread (Threads forum at JavaRanch)

    www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread 1

    posted 6/28/2013 8:42:26 PM

    A friendlyplace for

    programming

    greenhorns!

    Big Moose Saloon Search | Java FAQ | Recent Topics

    Register / Login

    JavaRanch Java Forums Java Threads and Synchronization

    Author Producer Consumer Problem using Thread

    V K GuptaRanch Hand

    Joined: Aug 07,2008Posts: 55

    Hi Friends,

    Please help me with the Producer Consumer Problem using Thread in Java. I have written the program for Producer Consumer

    Problem using Thread but my program is incomplete , so I want that somebody make the correction and addition in my program

    to make it complete so that i can understand Threads .

    class A {

    int value;

    public void setA(int v) {

    value=v;

    }

    public int getA() {

    return value;

    }

    }

    class put implements Runnable {

    A obj;

    public void run() {

    for(int i=1;i

  • 8/22/2019 Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

    2/13

    7/14/13 Producer Consumer Problem using Thread (Threads forum at JavaRanch)

    www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread 2

    posted 6/30/2013 11:25:26 AM 1

    posted 7/1/2013 1:23:17 PM

    public void run() {

    while(true) {

    System.out.println(obj.getA());

    if(obj.getA() == 10)

    break;

    }

    }

    }

    public class X1 {

    public static void main(String arg[]) {

    A obj = new A();

    put p = new put(obj);

    get g = new get(obj);

    Thread p1 = new Thread(p);

    Thread g2 = new Thread(g);

    p1.start();

    g2.start();

    }

    }

    Chan AgRanch Hand

    Joined: Sep 06,2012Posts: 154

    You could tell us how you expect your program to behave. Do you mean your producer and consumer threads need to be

    synchronized? If yes, then what kind of synchronization are you looking for? Are you ok if the get thread misses a couple of

    values set by the other thread, i.e you just want that each of these threads taken separately behaves in a consistent way as

    regards the shared object-- this is relatively simple. Or do you also want that the updates to the state of the shared object are

    also no t missed - in which case you might need to have some custom wait, notification logic build up.

    Also it seems, you aren't new to ranch. You might want to consider using the code tags to make your ques tion readable.

    Also unless you don't have a strong reason to not follow Java naming conventions, I believe you might want to consider

    changing your class names and method names.

    Thanks,

    Chan.

    V K GuptaRanch Hand

    Joined: Aug 07,2008Posts: 55

    Thanks Chang Ag,

    I have re-written by program according to Java Conventions.

    Second Question ?

    I need producer and consumer thread to be synchronized . If producer produce one item then it should notify the consumer

    thread about it and after the consumer consume the item it should notify the producer to produce again and it should go on.

    consumer thread should not miss any produce item by the producer thread.

    v iew p la in copy to c li pboard pri nt ?

    Note: Tex t content in the code block s is automatically word-wrapped

    01. class Item {02.03. int content;04.05. publicvoid setContent(int content) {06. this.content=content;07. }08.09. publicint getContent() {10. return content;

    2

    http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/forums/user/profile/272563http://www.coderanch.com/t/410859/java/java/String-StringBuffer-StringBuilder-Performance
  • 8/22/2019 Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

    3/13

    7/14/13 Producer Consumer Problem using Thread (Threads forum at JavaRanch)

    www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread 3

    posted 7/1/2013 1:27:26 PM

    posted 7/1/2013 3:15:53 PM 1

    .12. }13.14. class Producer implements Runnable {15.16. Item objItem;17.18. Producer(Item objItem) {19. this.objItem=objItem;20. }21.22. publicvoid run() {23. for(int i=1;i

  • 8/22/2019 Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

    4/13

    7/14/13 Producer Consumer Problem using Thread (Threads forum at JavaRanch)

    www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread 4

    . re urn content;13. }14. }15.16. class Producer implements Runnable {17.18. Item item;19.20. Producer(Item item) {21. this.item=item;22. }23.24.25. public Item getItem() {26. return item;

    27. }28.29.30. publicvoid setItem(Item item) {31. this.item = item;32. }33.34.35. publicvoid run() {36. int i =0;37. synchronized(this)38. {39. while(true)40. {41. ++i;42. if (i==10) return;43. System.out.println("Putting the value in item " + i );44. item.setContent(i);45. notify();

    46. try{47. wait();48. }49. catch(InterruptedException e){50. e.printStackTrace();51. }52. }53. }54. }55. }56.57.58. class Consumer implements Runnable {59.60. Producer producer;61.62.63. Consumer(Producer producer) {64. this.producer = producer;

    65. }

    66.67.68. publicvoid run()69. {70. synchronized(producer)71. {72. while(true){73. System.out.println("Consuming " +producer.getItem().getContent());74. producer.notify();75. try {76. if(producer.getItem().getContent() == 9)77. return;78. producer.wait();79. } catch (InterruptedException e) {80. // TODO Auto-generated catch block81. e.printStackTrace();82. }83.84. }85.86. }87.88. }89. }90.91. publicclass Execute{92.93. publicstaticvoid main(String arg[]) {94. Item item1 = new Item();95.96. Producer producer = new Producer(item1);97. Consumer consumer = new Consumer(producer);98.99. Thread producerThread = new Thread(producer);100. Thread consumerThread = new Thread(consumer);101.102. producerThread.start();

  • 8/22/2019 Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

    5/13

    7/14/13 Producer Consumer Problem using Thread (Threads forum at JavaRanch)

    www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread 5

    posted 7/1/2013 7:08:36 PM 1

    posted 7/1/2013 9:29:34 PM

    103. consumerThread.start();104. }105. }

    Request others to provide feedback, so we may all learn.

    Thanks,

    Chan.

    Steve LukeBartender

    Joined: Jan 28,2003Posts: 3159

    I like...

    V K Gupta wrote:

    please reply

    Hi V K Gupta, You posted this all of four minutes a fter your previous post. The good folks on this forum are volunteers and have

    their own things to do: they aren't here to read and respond to your posts within seconds of your posting. Even if they were,

    allowing just four minutes between prods hardly gives time to understand the code you posted an provide a detailed response

    (after all if it were that easy you probably wouldn't have needed the he lp, you are clearly bright, so what is hard for you is not

    going to be easy for anyone else). So for next please EaseUp (

  • 8/22/2019 Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

    6/13

    7/14/13 Producer Consumer Problem using Thread (Threads forum at JavaRanch)

    www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread 6

    posted 7/2/2013 11:12:34 AM

    2012Posts: 154

    , .

    Thanks so much for such an informative and constructive feedback. I greatly appreciate it.

    Based on your suggestions, I have reworked on my code to take care of point 1 ( what if consumer gets the lock first ) by

    having an extra cond ition in the run method of the Consumer that can issue an extra notify() if that condition is met. I'm not

    sure if this is a graceful solution to handle the issue-- it's like too many conditions based on hard coded data va lues which

    makes your system difficult to be reused ( Just a guess). I'd like to post my solution here so I could (hope to) get a feedback

    again but I can't steal this pos t from the OP w ho reserves the first right to work on it and may have a bette r solution than mine

    So I'll wait for a while. :-)

    You almost provided us with the so lution for point 2 ( nested locks ). So this part was easy. Thanks.

    BlockingQueue description provided by you seems like a very pretty solution. It seems like a nice advanced construct in Java

    that I'd like to cover as soon as I can. Once I've studied about it, I will come back to this post to implement this requirement (

    point 1 might become very easy then ) using a BlockingQueue.

    Thanks,

    Chan.

    Chan AgRanch Hand

    Joined: Sep 06,2012Posts: 154

    Greetings,

    It seems I didn't do it right the second time too. :-) The extra notify() and extra w ait() was redundant and no t 'properly planned

    code. Skipping past how I didn't do it right the second time, here is my new solution.

    v iew p la in copy to c li pboard pri nt ?

    Note: Tex t content in the code block s is automatically word-wrapped

    01. package ThreadExamples;02.03. class Item {04.05. privatevolatileint content;06.07. publicvoid setContent(int content) {08. this.content=content;09. }10.11. publicint getContent() {12. return content;13. }14. }15.16. class Producer implements Runnable {17.18. private Item item;19.20. Producer(Item item) {21. this.item=item;22. }23.24.25.26. publicvoid run() {27. int i =0;

    28. synchronized(item)29. {30. while(true)

    31. {32. ++i;33. if (i==10) return;34. System.out.println("Producing " + i );35. item.setContent(i);36. item.notify();37. try38. {39. item.wait();40. }41. catch(InterruptedException e)42. {43. e.printStackTrace();44. }45. }46. }47. }48. }49.

    50.

    2

    2

    http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.htmlhttp://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html
  • 8/22/2019 Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

    7/13

    7/14/13 Producer Consumer Problem using Thread (Threads forum at JavaRanch)

    www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread 7

    posted 7/2/2013 4:46:32 PM 1

    51. class Consumer implements Runnable {52.53. private Item item;54.55.56. Consumer(Item item) {57. this.item = item;58. }59.60.61. publicvoid run()62. {63. synchronized(item)64. {65. while(true){66.67. if (item.getContent()!=0)68. System.out.println("Consuming " +item.getContent());69. item.notify();70. try71. {72. if(item.getContent() == 9)73. return;74. item.wait();75. }76. catch (InterruptedException e)77. {78. e.printStackTrace();79. }80.81. }82.83. }84. }85. }86.87. publicclass Execute{88.89. publicstaticvoid main(String arg[]) {90. Item item1 = new Item();91.92. //new Thread( new Producer(item1)).start();

    93. new Thread( new Consumer(item1)).start();94. new Thread( new Producer(item1)).start();95. }96. }

    Am I doing it right this time ( let us put aside finer solutions involving BlockingQueue for now cause I will be ab le to ge t to those

    pretty things late r I guess-- Much later)?

    Thanks,

    Chan.

    Steve LukeBartender

    Joined: Jan 28,

    2003Posts: 3159

    I like...

    Chan Ag wrote:

    Am I doing it right this time ( let us put aside finer solutions involving BlockingQueue for now cause I will be able to get to those pretty

    things later I guess-- Much later)?

    You are, as long as ...

    v iew p la in copy to c li pboard pri nt ?

    Note: Tex t content in the code block s is automatically word-wrapped

    01. class Consumer implements Runnable {02. ...03. publicvoid run()04. {05. ...06.

    6

    http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.htmlhttp://www.coderanch.com/how-to/java/BumperStickershttp://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html
  • 8/22/2019 Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

    8/13

    7/14/13 Producer Consumer Problem using Thread (Threads forum at JavaRanch)

    www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread 8

    posted 7/3/2013 1:26:44 AM

    07. if (item.getContent()!=0)08. System.out.println("Consuming " +item.getContent());09. }10. }

    you know tha t zero is not a valid value. You make two such assumptions in your code: 1) that 0 means producing has not

    started, and 2) 9 is the last value. Again, in your specific case, that works. Do you think you could make the system work with

    any value?

    Chan Ag

    Ranch Hand

    Joined: Sep 06,2012Posts: 154

    Thanks Steve for the feedback. I've been working on your suggestions. Yeah, even I don't like the assumptions ( the hard

    coded values) in the code.

    I've been trying to remove the dependency on hard coded values to start/stop/manage the producer and consumer logic. Didn't

    realize it would be so difficult but it turns out that it is/was ( depending on whe ther it is still close to at least a decent solution )

    It has taken me a good amount of time to come up with even the current solution.

    I have used a helper class, SharedResource, that encapsulates the shared resource ( i.e Item object ) and a boolean

    contentChanged. Every time producer changes the value of the item object, it also se ts this flag and consumer clears this flag

    after consuming the value. This change could take care of ensuring that the consumer consumed a value only after producer

    had produced one regardless of which thread sta rted first. But once producer thread was dead, I could not find a nice logic to

    stop the consumer loop from wa iting. All I could think of was making the consumer wait for a few seconds and if it does not

    receive a notification in that period and the content hasn't changed in this period, producer is likely dead. Not sure how else I

    can make consumer thread more intelligent. I also considered add ing another flag in the SharedResource class calleddoneP roducing or something that the producer could set and consumer could poll. But that idea didn't appea l to me much. But

    still, is that what good programmers should do?

    Here is what I have.

    v iew p la in copy to c li pboard pri nt ?

    Note: Tex t content in the code block s is automatically word-wrapped

    01. package ThreadExamples;02.03. class Item04. {05.06. privatevolatileint content;07.

    08. publicvoid setContent(int content)09. {10. this.content = content;11. }12.13. publicint getContent()14. {15. return content;16. }17. }18.19. class SharedResource20. {21.22. private Item item;23. privateboolean contentChanged;24.25. public Item getItem()26. {

    27. return item;28. }29.30. publicboolean isContentChanged()31. {32. return contentChanged;33. }34.35. publicvoid setContentChanged(boolean contentChanged)36. {

    37. this.contentChanged = contentChanged;38. }39.40. public SharedResource(Item item)41. {42. super();43. this.item = item;44. this.contentChanged = false;

    2

    http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#
  • 8/22/2019 Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

    9/13

    7/14/13 Producer Consumer Problem using Thread (Threads forum at JavaRanch)

    www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread 9

    .46. }47.48. class Producer implements Runnable49. {50.51. private SharedResource resource;52. privatestaticfinalint producingLimit = 10;53.54. Producer(SharedResource resource)55. {56. this.resource = resource;57. }58.59. publicvoid run()

    60. {61. System.out.println("Producer started");62. int counter =0;63. synchronized (resource)64. {65. while (counter < producingLimit)66. {67. while (resource.isContentChanged())68. {69. try70. {71. System.out.println("Producer waiting for consumer");72. resource.wait(2000);73. if (resource.isContentChanged())74. {75. System.out.println("Consumer likely dead. I must die too.");76. return;77. }78. }

    79. catch (InterruptedException e) {80. e.printStackTrace();81. }82.83. }84. counter++;85. System.out.println("Producing " + counter);86. resource.getItem().setContent(counter);87. resource.setContentChanged(true);88. resource.notify();89. }90. }91. }92. }93.94. class Consumer implements Runnable95. {96. private SharedResource resource;97.

    98. Consumer(SharedResource resource)99. {100. this.resource = resource;101. }

    102.103. publicvoid run()104. {105. System.out.println("Consumer started");106. synchronized (resource)107. {108. while (true)109. {110. while (!resource.isContentChanged())111. {112. try113. {114. System.out.println("Consumer waiting for producer");115. resource.wait(3000);116. if (!resource.isContentChanged())

    117. {118. System.out.println("Producer likely dead. I must die too.");119. return;120. }121. }122. catch (InterruptedException e)123. {124. e.printStackTrace();125. }126. }127. System.out.println("Consuming " + resource.getItem().getContent());128. resource.setContentChanged(false);129. resource.notify();130. }131.132. }133. }134. }135.

  • 8/22/2019 Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

    10/13

    7/14/13 Producer Consumer Problem using Thread (Threads forum at JavaRanch)

    www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread 10

    136. publicclass Execute {137.138. publicstaticvoid main(String arg[]) {139. SharedResource resource = new SharedResource(new Item());140.141. //new Thread(new Producer(resource)).start();142. //for (int i = 0; i < 100000; i++);143. new Thread(new Consumer(resource)).start();144. for (int i = 0; i < 100000; i++);145. new Thread( new Producer(resource)).start();146.147. }148. }

    Here are the two sets of outputs.

    Producer started

    Producing 1

    Producer wa iting for consumer

    Consumer started

    Consuming 1

    Consumer wa iting for producer

    Producing 2

    Producer wa iting for consumer

    Consuming 2

    Consumer wa iting for producer

    Producing 3

    Producer wa iting for consumer

    Consuming 3

    Consumer wa iting for producer

    Producing 4

    Producer wa iting for consumer

    Consuming 4

    Consumer wa iting for producer

    Producing 5

    Producer wa iting for consumer

    Consuming 5

    Consumer wa iting for producer

    Producing 6

    Producer wa iting for consumer

    Consuming 6

    Consumer wa iting for producer

    Producing 7

    Producer wa iting for consumer

    Consuming 7

    Consumer wa iting for producer

    Producing 8

    Producer wa iting for consumer

    Consuming 8

    Consumer wa iting for producer

    Producing 9

    Producer wa iting for consumer

    Consuming 9

    Consumer wa iting for producer

    Producing 10

    Consuming 10

    Consumer wa iting for producerProducer likely dead. I must die too.

    Consumer started

    Consumer wa iting for producer

    Producer started

    Producing 1

    Producer wa iting for consumer

    Consuming 1

    Consumer wa iting for producer

    Producing 2

    Producer wa iting for consumer

    Consuming 2

    Consumer wa iting for producer

  • 8/22/2019 Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

    11/13

    7/14/13 Producer Consumer Problem using Thread (Threads forum at JavaRanch)

    www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread 11

    posted 7/3/2013 3:55:51 AM 1

    Producer wa iting for consumer

    Consuming 3

    Consumer wa iting for producer

    Producing 4

    Producer wa iting for consumer

    Consuming 4

    Consumer wa iting for producer

    Producing 5

    Producer wa iting for consumer

    Consuming 5

    Consumer wa iting for producerProducing 6

    Producer wa iting for consumer

    Consuming 6

    Consumer wa iting for producer

    Producing 7

    Producer wa iting for consumer

    Consuming 7

    Consumer wa iting for producer

    Producing 8

    Producer wa iting for consumer

    Consuming 8

    Consumer wa iting for producer

    Producing 9

    Producer wa iting for consumer

    Consuming 9

    Consumer wa iting for producer

    Producing 10

    Consuming 10

    Consumer wa iting for producer

    Producer likely dead. I must die too.

    Is it better now? Is< stop after value hasn't changed even though the wait time is elapsed> a decent approach to stop the

    threads in this scenario? What would you say?

    Thanks and Greetings,

    Chan.

    Steve LukeBartender

    Joined: Jan 28,2003Posts: 3159

    I like...

    Chan Ag wrote:

    But once producer thread was dead, I could not find a nice logic to stop the consumer loop from waiting. All I could think of was making

    the consumer wait for a few seconds and if it does not receive a notification in that period and the content hasn't changed in this period,

    producer is likely dead. Not sure how else I can make consumer thread more intelligent. I also considered adding another flag in the

    SharedResource class called doneProducing or something that the producer could set and consumer could poll. But that idea didn't

    appeal to me much.

    I am not a pa rticular fan of the timeout approach, because it is rather delicate if the amount of time to do the production varies

    or there can be hickups (if it was always fast there would be little reason to use separate threads...) There are two normal

    approaches:

    1) Set a flag. You already thought of this one, and I think the problem you seem to have w ith it is it is 'yet another flag' to set.To get around tha t (sort of) you could use a state instead of flags. For example:

    v iew p la in copy to c li pboard pri nt ?

    Note: Tex t content in the code block s is automatically word-wrapped

    01. publicenum DataState { INIT, PRODUCED, CONSUMED, DONE }

    Some state variable in SharedResources starts out as INIT. When the Producer first sets a value it sets the state to PRODUCED

    as it sets the new value, then waits for the CONSUMED state. When it has produced the last result, instead of setting the

    PRODUCED state it sets the DONE state. Meanwhile the Consume waits for the PRODUCED state, and gets the value. As it gets

    the value it sets the sta te to CONSUMED, then before wa iting again it checks for the DONE state, and when it gets it, it stops.

    This way you get one variable which descriptively replaces both the contentChanged flag you already have and the

    productionComplete flag.

    6

    http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/how-to/java/BumperStickers
  • 8/22/2019 Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

    12/13

    7/14/13 Producer Consumer Problem using Thread (Threads forum at JavaRanch)

    www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread 12

    posted 7/3/2013 7:15:46 PM

    se a o son . o son s a spec c o ec a e ro ucer se s a a never s ou come up as a na ura va ue o

    production and (b) when encountered causes the consumer to die. This is much eas ier to do using Object references than

    primitive data. An example:

    v iew p la in copy to c li pboard pri nt ?

    Note: Tex t content in the code block s is automatically word-wrapped

    01. class Item02. {03. publicstaticfinal Integer POISON_PILL = new Integer(-1);04. privatevolatile Integer content;05.06. publicvoid setContent(Integer content)07. {

    08. this.content = content;09. }10.11. publicvoid getContent()12. {13. returnthis.content;14. }15. }16.17. class Producer18. {19. //...20. while (counter < producingLimit)21. {22. //...23. counter++;24. System.out.println("Producing " + counter);25. item.setContent(counter);26. //...

    27. }28. //done producing, kill the consumer29. item.setContent(Item.POISON_PILL);30. //...31. }32.33. class Consumer34. {35. //...36. while(/* condition...? */true)37. {

    38. //...39. Integer value = item.getContent();40.41. // Note: Use the == not .equals(), one of those few instances where we compare42. // reference equality: we want to die on the POISON_PILL only, not on an Integer th

    at happens43. // to have the same value as it...

    44. if (value == Item.POISON_PILL)45. {46. return; // consumer dies47. }48. else49. {50. // ... consumer continues with value51. }52. }53. //...54. }

    Now, I haven't tested with Integers, I am not sure if there are gotchas in this particular code (but it would be easy to test, just

    cycle through -10 to 10 and make sure it doesn't kill the consumer). But this is the strategy I almost always implement my code

    (usually because I am not producing primitives, but more complex Data Access Objects). It also translates to using a Queue...

    Chan AgRanch Hand

    Joined: Sep 06,2012Posts: 154 public enum DataState { INIT, PRODUCED, C ONSUMED, DONE }

    Wow . This is brilliant. Four clean, neat enum objects. One reference. And it's sorted. Wow. Very creative. Wonder why I couldn't

    think of it.

    Thanks a lot, Steve.

    I think the problem you seem to have with it is it is 'yet another flag' to set

    2

    http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#http://www.coderanch.com/t/614729/threads/java/Producer-Consumer-Thread#
  • 8/22/2019 Producer Consumer Problem Using Thread (Threads Forum at JavaRanch)

    13/13

    7/14/13 Producer Consumer Problem using Thread (Threads forum at JavaRanch)

    posted 7/5/2013 3:24:39 AM

    Yes, exactly. I felt all I was do ing is - go create another flag. Every time. Come a new s ituation, all I could think of was have

    another flag. And the worst thing is this flag had to be a shared flag.

    I realize they use PoisonKill a lot many times in my current project and one of the default PoisonKill value they have he re is the

    String "-999". But it's a different programming language ( a proprietary programming language). I didn't know there was a term

    for 'PoisonKill' values. I think it's a good idea depending on the implementation. For this case I think enum reference approach is

    better though. I say this because we are also setting Item content to the PoisonKill value and that is not where PoisonKill

    belongs . Also like you said, it's an int. I like your explanation of why if we 'd ever use Po isonKill approach, we should always test

    using ==. Not sure if they've given due cons ideration to that in our project, but I'd check.

    Just a side note --

    Given that today I've started studying about volatile variables, I have also started re-evaluating my solution with respect to

    everything I'm studying. One of the things I kept on thinking about today was I have encapsulated item and the flag in an

    object and my run has a synchronized block on that object, not on item. So item can still be inconsistent. main() method still has

    item reference and hence I should have synchronized those b locks on item object. Also I was thinking content in Item is private

    and there are only getters and setters. Hence having content variable as a volatile variable was not a necessity. But again my

    synchronized blocks ( synchronized on another object) are accessing it - one is even do ing a ++ operation on the content. So I

    should have it as volatile. And then I thought- should it be better to have synchronized b locks synchronize on

    resource.getItem(). Just explaining my state o f mind. Not rea lly seeking help w ith it currently cause I feel as I study further, my

    understand ing will improve. Synchronized methods and blocks come next in the book I'm using as my reference.

    And if there are things I'd still need he lp with, I'm sure you guys will help me like you have so far. All this help means a lot to

    me. Thanks.

    Regards,

    Chan.

    Chan AgRanch Hand

    Joined: Sep 06,2012Posts: 154

    I tried to find some of the answers myself, but it seems I still require guidance. I've posted my questions in a separate, new

    post. Here is the link, if you'd like to take a look.

    http://www.coderanch.com/t/615123/java/java/synchronized-blocks-methods

    I'd appreciate any help I can get on the subject.

    Thanks,

    Chan.

    I agree. Here's the link: http://aspose.com/file-tools

    subject: Producer Consumer Problem using Thread

    Similar Threads

    Important, about threads

    static synchronized method

    Newbie Producer Consumer Problem

    Need he lp in code rega rding join()

    Explain me this output (notify)

    All times above are in your local time zone & fo rmat.T he current ranch time (no t your local time) is Jul 14, 2013 08:24:49 .

    Contact Us | Powered by JForum | Copyright 1998-2013 Paul Wheaton

    2

    http://www.javaranch.com/paul-wheaton.jsphttp://www.jforum.net/http://www.coderanch.com/how-to/code/ContactUshttp://www.coderanch.com/t/234180/threads/java/Explain-output-notifyhttp://www.coderanch.com/t/583455/threads/java/code-joinhttp://www.coderanch.com/t/456320/threads/java/Newbie-Producer-Consumerhttp://www.coderanch.com/t/374052/java/java/static-synchronized-methodhttp://www.coderanch.com/t/194589/java-programmer-SCJP/certification/Important-threadshttp://www.coderanch.com/forums/banner/redirect/544http://www.coderanch.com/t/615123/java/java/synchronized-blocks-methods