aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes wait/notify deadlock Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "wait/notify deadlock" Watch "wait/notify deadlock" New topic
Author

wait/notify deadlock

Bob CHOI
Ranch Hand

Joined: Nov 10, 2006
Posts: 127
To avoid wait/notify deadlock, the wait thread must aquire the object lock prior to the notify thread, how to gaurantee this? Thanks!


Hard work rewards
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Originally posted by Bob CHOI:
To avoid wait/notify deadlock, the wait thread must aquire the object lock prior to the notify thread, how to gaurantee this? Thanks!


Instead of using the order of wait() and notify(), a better solution is to check the state upon waiting. Meaning...

- Before calling wait() make sure that it is in a state that should wait.
- Upon returning from wait, make sure that it is in an okay state. Otherwise, go back to a wait state.
- Set the state prior to sending the notification.

If you do this correctly, order won't matter... For example, in the following code:



It doesn't matter if the process() or waitForCompletion() method gets called first.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Bob CHOI
Ranch Hand

Joined: Nov 10, 2006
Posts: 127
Thanks, Henry. brilliant answer!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: wait/notify deadlock