This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wait/notify deadlock

 
Bob CHOI
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To avoid wait/notify deadlock, the wait thread must aquire the object lock prior to the notify thread, how to gaurantee this? Thanks!
 
Henry Wong
author
Marshal
Pie
Posts: 20902
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Bob CHOI
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Henry. brilliant answer!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic