Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to waiting thread if notify() is not called?

What happens to waiting thread if notify() is not called? Is this spurious wakeup?

like image 362
amitguptageek Avatar asked Mar 29 '15 16:03

amitguptageek


People also ask

What if I invoke notify () and there is no thread waiting?

In other words, if the notify() method is called when no other thread is waiting, notify() simply returns and the notification is lost. A thread that later executes the wait() method has to wait for another notification to occur.

Can we use wait without notify?

You need notify or notifyAll to awaken the thread from its wait state. In your sample the code would enter the wait and stay there (unless interrupted).

What is the purpose of the wait () notify () and notify all () methods?

The wait() method causes the current thread to wait until another thread invokes the notify() or notifyAll() methods for that object. The notify() method wakes up a single thread that is waiting on that object's monitor. The notifyAll() method wakes up all threads that are waiting on that object's monitor.

When wait () notify () notifyAll () methods are called does it releases the lock or holds the acquired lock?

8 Answers. Save this answer. Show activity on this post. No -- notify / notifyAll don't release locks like wait does.


1 Answers

If a waiting Thread is not notified by calling notify() or notifyAll() on the object the said thread is waiting on, then any one of the following may happen:

  • the Thread keeps waiting in the object's wait pool
  • the Thread becomes runnable if a timeout was specified and the time elapses
  • the Thread gets interrupted and becomes runnable again
  • the Thread wakes up for no reason at all i.e. it was neither notified nor interrupted

The last case is known as a spurious wake-up and is one of the reasons why upon wake-up a Thread should always check whether the condition it was waiting for is true or not. If not, the Thread should call and go wait() again.

like image 101
Ravi K Thapliyal Avatar answered Sep 19 '22 02:09

Ravi K Thapliyal