wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt on wait method in Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt on wait method in Threads" Watch "Doubt on wait method in Threads" New topic
Author

Doubt on wait method in Threads

Aravind Jerubandi
Ranch Hand

Joined: Dec 17, 2006
Posts: 49
The question # 10 in the Threads chapter in K&B book is as follows:

Assume following method is properly synchronized and called from thread A on an object B:
wait(2000);
After calling this method, when will thread A becomes a candidate to get another turn at the CPU?

A. After object B is notified, or after two seconds.
B. After the lock on B released, or after two seconds.
C. Two seconds after object B is notified.
D. Two seconds after lock B is released.

I understand that option 'A' is correct. But i'm unable to understand why the option D is not correct. Doesn't thread A come to Runnable pool 2 seconds after the wait gets executed (i.e 2 seconds after lock B releases)?

I don't understand the difference between the second part in option A i.e. or after two seconds and option D.

Someone please clarify.


-Aravind<br />SCJP 5.0 (91%), Preparing for SCBCD.
Bob Ruth
Ranch Hand

Joined: Jun 04, 2007
Posts: 320
Here is the way to look at that: when you pass a timeout to wait, you are now waiting on two unrelated things - the notify() from whoever is releasing the lock, or, a timeout, one of the two.

A is obvious but D tries to say that, after the lock is released there will be a 2 second delay and THEN this waiting thread will go runnable and that is not the case. If the notify() call happens as it normally should your thread will be marked runnable right NOW. If notify() doesn't happen within 2 seconds then your thread will be marked runnable.

The timeout is a safety feature to keep you from waiting forever on a notify() that isn't coming for one reason or another.


------------------------
Bob
SCJP - 86% - June 11, 2009
Aravind Jerubandi
Ranch Hand

Joined: Dec 17, 2006
Posts: 49
Thanks Bob!
 
Consider Paul's rocket mass heater.
 
subject: Doubt on wait method in Threads
 
Similar Threads
S&B 1.5 Chapter 9, question 10
Thread Question - wait() method
Thread states and Object lock
Thread Question
Wait with timeout