views:

147

answers:

3

I have a question. In the following code, if a thread were blocked at wait statement, and another thread attempts to execute foo(), would the hello world message be printed? and Why?

synchronized foo(){
    system.out.println("hello world");
    .....
    wait();
    .....
}
+1  A: 

Yes.

wait(); gives up the monitor, so yes , if Thread A is blocked in wait(); , Thread B would be able to enter foo and print hello world

nos
+3  A: 

For a thread to enter the method foo it needs to have a lock on the object (monitor) which contains the foo method. When the wait is executed the thread releases the lock on the monitor. So if another thread attempts to execute foo and (say it could acquire the lock) then it would print the "hello world" message.

sateesh
+1 I didn't know that `wait` causes the thread to release the monitor. But then it needs to reacquire a lock on the monitor to continue once `notify` has been called... So basically calling `wait` inside a `synchronized` method is not a good idea, it seems?
Yar
@yar Calling `wait` inside `synchronized` methods is for sure better idea than calling outside them. Calling `wait` without owning object's lock ends with `IllegalMonitorStateException`.
Tadeusz Kopec
@Tadeusz Kopec Oh, my bad.
Yar
+1  A: 

It is also a best practice to wrap wait() invocation in a while . Reason: sporadic wake-up!

Loop
I'm not convinced by this. If the code uses `notify` rather than `notifyAll` then a "sporadic" wake-up is a result of a bug in your code. Isn't it better to find and fix the bug?
Stephen C
@Stephen - That assumption isnt correct. A sporadic wake up can be a product of OS wakeing a thread. Not wrapping the wait in a while is a ticking time bomb. The code can be perfectly fine and it still could fail.
John V.
@John W - can you show me in the Java documentation where it says that can happen?
Stephen C
Check Object#wait java doc: http://java.sun.com/javase/6/docs/api/java/lang/Object.html#wait(long)
Loop