• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java 5 Concurrency solution  RSS feed

 
Kousik Majumder
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I was trying to resolve the problem of Producer Consumer by Java 5 Concurrency API's. But the code below does not solve the problem. Can somebody help me what am I missing?
What I want is pop() will wait untill there is something to pop. But this is not happening.




Output:-


Thanks in advance.

- Kousik
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your pop() method looks like this:

When the oldHead is null (the stack is empty), you return null. If you don't want the method to return in this case, you shouldn't return anything. Instead you should do something else. You could either poll in a loop, or have a Lock/Condition or perhaps a Semaphore you wait on to block and un-block when there is an element available.
 
Kousik Majumder
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI Steve,

Thank you for your quick reply. But I still do not understand what code should I write to wait for any element to be inserted in stack(without using Object.wait()) and also how do I handle the situation when all the elements are popped up already.

Thanks,
Kousik
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kousik Majumder wrote:HI Steve,

Thank you for your quick reply. But I still do not understand what code should I write to wait for any element to be inserted in stack(without using Object.wait()) and also how do I handle the situation when all the elements are popped up already.

Thanks,
Kousik


I gave some hints there. Look up java.util.concurrent.Semaphore, or java.util.concurrent.locks.Lock and java.util.concurrent.locks.Condition to see how they get used.

How do you deal with 'when all the elements are popped up already?' Define what you mean by when all the elements are popped, what is the difference between that and the case when the stack is empty and you should wait to pop the next item? Once you answer that you can decide what you want to do when you reach that situation.
 
Kousik Majumder
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thank you Steve. I understood now. My confusion was regarding how long should I wait for stack to fill. The answer is Condition.

Thanks,
-Kousik
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!