Wednesday, 24 April 2019

Wait, notify and notifyAll method in Object Class


We usually get surprise when these methods are present in Object class however they only used in Threading Concepts.

 Wonder WHY??????

Basically to understand the reason behind placing these 3 method in Object class we will describe what these methods are made for

"Wait , notify , notifyAll method are used for communication between two threads."

 When any thread is performing update operation on object and other thread is expecting update operation-on that thread (let say Producer , Consumer problem) then Thread who is expecting the update need to calls the wait method method on that object. Now that object can be anything it can be Student , it can be Stack , it can be Queue ,It can be Map Object. Hence wait method should be available to all the object . 

As Object Class is Parent Class of all classes, hence to avoid this kind of Chaos. Wait, notify and notifyAll became the part of Object Class. 

Same applicable to notify (to inform current waiting thread) and notifyAll(to inform all waiting threads) method. 

Now, its time to reveal some more interesting facts about wait, notify and notifyAll method

To call wait, notify, notifyAll method on any object thread should be owner of the object 
or in other words thread should have lock of that object which means thread should be in synchronized area.

"Hence we can call wait , notify, notifyAll methods only from synchronized area else we will get runtime exception saying IllegalMonitorStateException."

The main difference between notify and notifyAll is: 

Suppose you have 10 different thread in waiting state for notification then notify method will notify only one thread out of that 10 thread randomly. However notifyAll will send a notification to all the waiting thread for that object.







ww
Happy Learning!! 

If I missed something or for any query please feel free to write :)

Wait, notify and notifyAll method in Object Class

We usually get  surprise  when these methods are present in  Object  class however they only used in  Threading  Concepts.   Wonder WHY?...