1.

Is It Important To Acquire Object Lock Before Calling Wait(), Notify() And Notifyall()?

Answer»

Yes, it’s mandatory to acquire object lock before calling these methods on object. wait(), notify() and notifyAll() methods are ALWAYS called from SYNCHRONIZED block only, and as soon as thread enters synchronized block it ACQUIRES object lock (by holding object monitor). If we call these methods without ACQUIRING object lock i.e. from outside synchronize block then java.lang. IllegalMonitorStateException is thrown at runtime.
Wait() method needs to enclosed in try-catch block, because it throws COMPILE time exception i.e. InterruptedException.

Yes, it’s mandatory to acquire object lock before calling these methods on object. wait(), notify() and notifyAll() methods are always called from Synchronized block only, and as soon as thread enters synchronized block it acquires object lock (by holding object monitor). If we call these methods without acquiring object lock i.e. from outside synchronize block then java.lang. IllegalMonitorStateException is thrown at runtime.
Wait() method needs to enclosed in try-catch block, because it throws compile time exception i.e. InterruptedException.



Discussion

No Comment Found