Why wait() and notify() called from synchronized context?

This is one of the most popular interview question and often asked in telephonic round of Java interviews.

In simple word we can understand that wait() and notify() methods are called from synchronized because after calling wait() method on object the current thread want to achieve a particular state before executing the block and its only possible if the thread gives signal to other threads via notify() method that the particular state has been achieved and to fulfill this condition the block inside which wait() and notify() methods are calling  should be synchronized in nature.

wait() and notify()

wait() and notify()/notifyAll() methods mostly used for inter-thread communication in Java. wait() method tells the current thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ) method. notify() wakes up the first thread that called wait() on the same object.

Following problems occurs in java if we do not call wait(), notify() or notifyAll() methods from synchronized context:

1) IllegalMonitorStateException will occur if we don’t call wait(), notify() or notifyAll() method from synchronized context.

2) Race condition between wait() and notify() could exists if we don’t call them inside synchronized method or block. This race condition is resolved by using synchronized keyword and locking provided by java.

Synchronize your Java object to allow mutual exclusive access of critical section to two threads. If your code is executing in multi-threaded environment, you need synchronization for objects, which are shared among multiple threads, to avoid any corruption of state or any kind of unexpected behavior. synchronized keyword in Java provides locking, which ensures mutual exclusive access of shared resource and prevent data race.

Java Professional with rich experience in Java development.
– Designing and developing high-volume, low-latency applications with high-availability and performance.
– Writing well designed, robust and efficient code.

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By : XYZScripts.com