This week's book giveaway is in the HTML/CSS/JavaScript forum.
We're giving away four copies of Practical SVG and have Chris Coyier on-line!
See this thread for details.
Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to solve this wait() and notify() issue?

 
Ajay Xavier
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

consider the following class



In the above code

1. is there any chance that wait() statement is getting executed in between the execution of call() method?
2. In the above code i experience the following problem
if isCompleted() returns true for the first time the notify() statement gets called before the execution of wait()which causes this thread to wait indefinitely. how to avoid this situation?

Regards,
Ajay.
 
Henry Wong
author
Sheriff
Posts: 22542
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
2. In the above code i experience the following problem
if isCompleted() returns true for the first time the notify() statement gets called before the execution of wait()which causes this thread to wait indefinitely. how to avoid this situation?


There are two rules that you should follow...

1. Never call wait() blindly. Always check to see if you should wait before calling wait. This check should be done within the synchronized block, due to race conditions.

2. Never assume that a return from wait() puts you in an okay state. Always check again to see if you should go back into a wait condition, when returning from wait.

Hence, you code should look like this...



Henry
 
Henry Wong
author
Sheriff
Posts: 22542
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One other issue... the wait() and notify() mechanism is for communication between multiple threads. If the thread that is calling notify(), is the same thread that is calling wait(), you can pretty much be assured that the notifications will not be recieved... as the thread that is supposed to be waiting is guarranteed *not* to be waiting when the notification is sent... :-)

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!