Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wait/notify

 
Theodore David Williams
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a consumer of an ArrayBlocking queue that is pulling from the queue one at a time, doing something with the object I pull off the queue and then waiting (wait()) until another thread tells it to wake up and pull the next item off the queue.


However when another thread calls the requestComplete() method my consumer does not wake up. Any ideas?
Thanks!
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, as you've shown it, the code ought to behave as you expect. But there are a few subtle indications that this isn't the real code -- for instance, the variable that holds the RequestConsumer is known by several different names -- so the real code may well have problems that aren't displayed in this simplified version.
 
Andrey Kozhanov
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code 'as is' doesn't compile, therefore it's hard to say, what's wrong. My suggestion is that you are synchronizing on different variables - that's why your 'notify' call is not working.
 
Sergey Babkin
author
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I remember correctly, wait()/notify() follows the Unix/POSIX model. That means, if notify() is called when the other thread hasn't called wait() yet, the notification will be lost and the reader will wait forever. The handler has to be written like this:



The posting has to be done like this:



You might think "but wait() will hold the synchronization when waiting!". Nope, it releases the synchronization when waiting, and then gets it back when notified, and does it atomically, avoiding the race.
 
Aditya Jha
Ranch Hand
Posts: 227
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a consumer of an ArrayBlocking queue that is pulling from the queue one at a time, doing something with the object I pull off the queue and then waiting (wait()) until another thread tells it to wake up and pull the next item off the queue.


A better strategy would be to wait if (or, while) the queue is empty, just like in a traditional reader-writer solution.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic