• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt on wait method in Threads

 
Aravind Jerubandi
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bob Ruth
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Aravind Jerubandi
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bob!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic