Reputation: 1087
Though there are lots of articles and SO posts on this topic , still i have some doubts. So please help me understand. Say i write :
1.Class A(){}
2.public static void main(String[] s){
3. A obj= new A();
4. synchronized(obj){
5. while(!condition)
6. obj.wait();
7. }
8.}
Now according to explanations ,if we don't use synchronized block, Thread woken-up from sleep may loose notifications. BUT line 6 released the lock on obj i.e. its monitor is owned by another thread. Now when that thread invoked notify() , how does this thread get notified since obj's monitor is not owned by this thread. Moreover , line 4 code executes only once ,NOT on each wake-up event of this thread. So what EXACTLY is NEED of synchronized before wait()?
Edit: "line 4 code executes only once" wrong assumption. Threads in synchronized blocks reacquire lock after they are resumed from sleep as mentioned in answer.Thanks
Upvotes: 1
Views: 135
Reputation: 614
"So what EXACTLY is NEED of synchronized before wait()?" : Condition is shared across the thread and any change in condition should be thread safe and that is reason for having synchronized. Here condition is not some random condition but this is something for which your thread is going wait for. Hope this helps.
Upvotes: 0
Reputation: 328735
It works as explained in the javadoc for Object#wait
, emphasis mine:
The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
so once the waiting thread is notified, it reacquires the monitor before proceeding to the next instruction (in your case: while(!condition)
).
Upvotes: 1