Friday, February 8, 2013

Why Wait() , Notify() and NotifyAll() is defined in Object Class..

This is one of most common interview question in java threading and many of us know the answer but couldn't be able to explain properly.
Here what I say..  Since wait, notify, notifyAll manipulates the LOCK, which is part of Object i.e thread takes or release the lock, which is part of Object/Class in java.  and these methods manipulate the lock, this is why they are defined at Object Class.

That's the reason we can call wait(), notify(), notifyAll() only within synchronized block/method. If you call wait( ) or notify( ) within a method that’s not synchronized, the program will compile, but when you run it you’ll get an IllegalMonitorStateException with the somewhat non-intuitive message “current thread not owner.”
Note that sleep( ), suspend( ), and resume( ) can all be called within non- synchronized methods since they don’t manipulate the lock.

In nutshell, Locks are made available on per Object basis i.e. any Object can be the monitor for a thread. The wait and notify are called on the monitor. The running thread checks with the monitor. So the wait and notify methods are in Object and not Thread.

Another reason for putting wait and notify could be that they are communication mechanism between two threads in Java. And Object class is correct place to make them available for every object if this mechanism is not available via any java keyword like synchronized

No comments:

Post a Comment