File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes Not sure why this code is deadlocking (From my SCJP book) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Not sure why this code is deadlocking (From my SCJP book)" Watch "Not sure why this code is deadlocking (From my SCJP book)" New topic
Author

Not sure why this code is deadlocking (From my SCJP book)

Chuu
Greenhorn

Joined: Aug 25, 2008
Posts: 3
While studying the SCJP I typed out a lot of the threading code because my brain doesn't process long code dumps very well. This code is taken from the Sanghera book, and is supposed to be a trivial example of wait/notify.



The output is supposed to be:



Which it is, 99%+ of the time. The thing is if I keep running it, eventually I will get this:



Thought it would be a good exercise to try to fix this, but I'm stumped and don't see the problem with the original code. Any help?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18825
    
  40

The problem is that the wrong target is awoken with the notify() method call.

For this code to work, the consumer *must* wake up the producer on notify() call. Since the consumers are being started, which takes some time, there is a good chance for this (since the consumer may not be waiting yet). However, if the consumer wakes up another consumer instead, the notification is just ignored as the consumer just goes back into a wait state -- and then, there will be nothing to wake up the producer.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Nitesh Kant
Bartender

Joined: Feb 25, 2007
Posts: 1638

BTW, it is not a deadlock, it is just a case of lost notification.

Here is the wiki entry for deadlock.


apigee, a better way to API!
 
 
subject: Not sure why this code is deadlocking (From my SCJP book)