aspose file tools*
The moose likes Threads and Synchronization and the fly likes wait/notify Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "wait/notify" Watch "wait/notify" New topic
Author

wait/notify

Theodore David Williams
Ranch Hand

Joined: Dec 21, 2009
Posts: 102
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

Joined: Jul 08, 2003
Posts: 24185
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Andrey Kozhanov
Ranch Hand

Joined: Mar 12, 2010
Posts: 79
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

Joined: Apr 05, 2010
Posts: 50
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

Joined: Aug 25, 2003
Posts: 227

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: wait/notify