views:

75

answers:

1

Hi,

I am going through a java 6 book. A sample code snippet is given below from Threads chapter, where I need a clarification

synchronized(a){ //The thread gets the lcok on 'a'
a.wait(2000);// Thread releases the lock and waits for notify only for maximum of two seconds, then goes back to runnable state
//The thread reacquires the lock
//More instructions here
}

Now my doubt is, after 2 seconds of wait time, to continue further code execution, the above code would require the lock on object 'a' and there is fair chance that the other thread (which is supposed to call notify() on a) might already be holding a lock on it.

So shouldn't the thread go to Blocking state after 2seconds wait, instead of Runnable state as mentioned above in the comments (in Line No. 2).

Kindly clarify what am I missing here.

Thanks & Regards, Harish

+1  A: 

If another thread has the lock on the object, then yes, you are correct, it will wait. The javadocs for wait state the following behavior when the specified amount of time elapses.

"The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked"

Jeff Storey
In the above statement, where it says "re-enabled for thread scheduling" in the first line, it means that it is Runnable state now. Right?But again the next line states that now it completes with other threads for right to synchronize (i.e. to attain the lock) - Then that would mean the thread in - Blocking state for object lockSo which one is correct? Is it in Runnable state or Blocking state?Please correct me if I am wrong anywhere.
Harish
If no other thread had the lock it would be runnable but if something else had the lock it would have to wait just like everyone else. You should write some tests to explore this behavior further.
Jeff Storey
Thanks for this info. I will try out some examples as suggested
Harish