File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Chuu
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BTW, it is not a deadlock, it is just a case of lost notification.

Here is the wiki entry for deadlock.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic