Interview Questions

Is it important to acquire object lock before calling wait(), notify() and notifyAll()?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

16. Is it important to acquire object lock before calling wait(), notify() and notifyAll()?

Yes, it’s mandatory to acquire object lock before calling these methods on object. As discussed above 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.

(Continued on next question...)

Other Interview Questions