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.