Sudhanshu Mishra wrote:Thanks for the reply,
but still have a confusion,silly though.If the thread is already going to lose the lock when it waits,then why in the first place give it the lock for object by synchronization?does synchronzation has really something to do with the waiting of thread,or is it meant for other code within the synchronized block?
I hope you understand my problem.
Please guide me through....
I guess Henry Wong has answered similar query by you
here, but I'll still try to elaborate.
As he has said, synchronization is for making sure that the condition on which you are waiting must be touched by only one thread at a time. If wait/notify does not exist in synchronized block, then we cannot guarantee that our code will be in 'synch'.
e.g. Let us take a producer-consumer example. Let us assume that
Java allows wait and notify without synchronization.
Now, here, since there is no synchronization, assume this scenario:
1) queue is empty
2) consumer reaches at line 7
3) producer starts, adds an object, notifies and gets out of the method
4) consumer starts to wait. It'll wait forever (unless some other producer wakes it up).
Thus, we can see our code is out of sync. This is just one example. Weird things can happen even after wait/notify (e.g. two threads simultaneously consuming same object and so on).
Now, check out the synchronized code:
Here, if scenario occurred similar to previously mentioned, we are still safe:
1) queue is empty
2) consumer reaches at line 10
3) producer is still not inside the synchronized block
4) consumer reaches at line 11, goes in waiting state and releases the lock
5) producer enters in synchronized block, adds a queue and notifies
6) since producer is finished, consumer again gets the lock
7) after line 11, consumer checks the while condition. it is now false and loop is broken
8) consumer goes to line 13, consumes the object.
This way, we are always sure that no two threads exists simultaneously in
critical section.
I hope this helps.