February 19, 2019

Wait, notify and notifyall. What is the difference between notify and notifyall.

Q1 :- How does Java maintains a record of threads waiting on an object?

Ans :- Each object has a waiting set. Every time a thread  calls wait on an object, that thread gets added in that waiting-set. So, a Set datastructure is used to maintain the record of waiting threads in java.

Q2 :- What is the difference between notify and notifyall.

Ans :- We know, when a thread calls wait over an object, the only way it can start executing correctly is to use notify or notifyall. I mean, thread can come out of waiting even if they get interrupted. But, we are only going to focus on notify and notifyall.By the name of these two functions, we can understand what it does. The notify function, notifies only one thread. And, there is no guarantee which thread will be removed from waiting state.While notifyall is meant to notify-all of the waiting threads.I mean, notify-all the waiting threads that they can start executing now.

Q3 :- What happens when notify is called on an object?

Ans :- When a notify is called on an object,  a thread from waiting-set is removed. As, set is an unordered datastructure there is no guarantee, which thread will get a chance to execute.

Q4 :- What happens when notifyall is called on an object?

Ans :- Then all the threads present in the waiting-set are removed from the waiting set of that object.

Q5 :- What happens, when a thread is removed from waiting set of an object?

Ans :- That thread becomes eligible for execution and depending on the availability of computing resources that thread will start executing.

Q6 :- When to use notify?

Ans :- If Only one thread can execute after monitor is released on the object, then we should call notify.

For example, If a producer produces only one element, consider synchronize queue. Another element is only produced after a consumer has removed that element from that queue. So, that producer can produce other element. Here, only one element is produced so only one consumer is required at a time. If in this case, we notifyall the consumers, then it is of no use.

In the scenario, where only one thread can execute after release of monitor on an object then use notify.

Q7 :- When to use notifyall?

Ans :- When mutiple threads can execute after release of the lock, then we should use notifyall.

For example, I have created a download manager, which checks for network connection and If the the network is up then it starts all the downloads. Here, we have a thread which repeatedly checks for connection and all other threads waits for this thread to give a green light, so that they can start executing.

So, here we need to call the notifyall, because, all threads are waiting for one single event to occur.


Tagged on: