Concurrency in Java: using wait(), notify() and notifyAll()

  • 4.0/5
  • 3936
  • Jul 20, 2024

Signaling is used to synchronise multiple threads by signalling to each other that a new thread can do something that was previously blocked by calling the wait() method.

In Java, thread signalling is implemented via the wait(), notify(), and notifyAll() methods that are part of the "Object" class.

A thread that calls "wait()" on any object becomes inactive (blocked) until another thread calls "notify()" or "notifyAll()" on that object.

In order to call "wait(), notify(), or notifyAll()" on an object, a thread must obtain the lock on that object first. That is, the calling thread must call wait(), notify(), or notifyAll() from inside a synchronized block or method.

If a thread tries to call "wait(), notify(), or notifyAll()" on an object without holding the synchronization lock on that object, an IllegalMonitorStateException is thrown.

In the example above, when a thread enters the synchronized block and calls wait() on the monitor object, the calling thread releases the lock on the monitor object and is "blocked" until another thread calls notify() or notifyAll() on the monitor object.

When another thread enters the synchronized block and calls the "notify()" method on the monitor object, it wakes up any one of the threads blocked by the wait() call on the same monitor object.

However, this awakened thread cannot exit the wait() method until the thread calling notify() has released the lock on the monitor object.

Multiple threads can call "wait()" on the same monitor object and thus become blocked waiting for a "notify() or notifyAll()" call.

Difference between notify() and notifyAll()

The main difference between the "notify()" and "notifyAll()" methods is that, if multiple threads are waiting on any locks in Java, the notify method sends a notification to only one of the waiting threads, while notifyAll informs all threads waiting on that lock.

If you use "notifyAll()", since all threads will be notified, they will compete for a lock, and the lucky thread that gets a lock can continue.

In a way, the notifyAll() method is safer because it sends a notification to all threads, so if any thread misses the notification, there are other threads to do the job.

Calling both of these methods does not give up the lock on the resource; rather, their job is to wake up the threads that have been sent to the waiting state using the "wait()" method.

It is mandatory to enclose wait() in a try-catch block because if a thread present in the waiting state gets interrupted, then it will throw an InterruptedException.

The wait() method variations

The wait() method has three variations:

1) wait(): This will cause the thread to wait until "notify()" or "notifyAll()" is called.

2) wait(long timeout): This will cause the thread to wait either until "notify()" or "notifyAll()" is called or until the timeout duration expires.

3) wait(long timeout, int nanoseconds): This will cause the thread to wait either until "notify()" or "notifyAll()" is called or until the timeout duration expires.

Missed Signals

A missed signal can occur when you have two threads where one calls "notify()" before the other calls "wait()".

In some cases, this may result in the waiting thread waiting forever and never waking up because the signal to wake up was missed.

In order to avoid losing signals, they should be stored in a member variable inside the signal class.

In the above-mentioned modified version of signalling implementation, the thread calling the "doNotify()" method sets the isSignalled variable to true before calling notify().

Likewise, the thread calling the "doWait()" method now checks the "isSignalled" variable before calling wait() and only calls wait() if no signal was received in between.

Exercise

Print alternate even and odd numbers using two threads

Given an integer "n," the task is to print numbers from "1" to "n" in increasing order using two threads.

Also, make sure that even numbers are printed by one thread and odd numbers are printed by other thread.

Print Even : 1
Print Odd : 2
Print Even : 3
Print Odd : 4
Print Even : 5
Print Odd : 6
Print Even : 7
Print Odd : 8
Print Even : 9
Print Odd : 10
Index
Modern Java - What’s new in Java 9 to Java 17

32 min

What is differences between JDK, JVM and JRE ?

2 min

What is ClassLoader in Java ?

2 min

Object Oriented Programming (OOPs) Concept

17 min

Concurrency in Java: Creating and Starting a Thread

12 min

Concurrency in Java: Interrupting and Joining Threads

5 min

Concurrency in Java: Race condition, critical section, and atomic operations

13 min

Concurrency in Java: Reentrant, Read/Write and Stamped Locks

11 min

Concurrency in Java: "synchronized" and "volatile" keywords

10 min

Concurrency in Java: using wait(), notify() and notifyAll()

6 min

Concurrency in Java: What is "Semaphore" and its use?

2 min

Concurrency in Java: CompletableFuture and its use

18 min

Concurrency in Java: Producer-consumer problem using BlockingQueue

2 min

Concurrency in Java: Producer-Consumer Problem

2 min

Concurrency in Java: Thread pools, ExecutorService & Future

14 min

Java 8 Lambdas, Functional Interface & "static" and "default" methods

28 min

Method Reference in Java (Instance, Static, and Constructor Reference)

9 min

What’s new in Java 21: A Tour of its Most Exciting Features

14 min

Java Memory Leaks & Heap Dumps (Capturing & Analysis)

9 min

Memory footprint of the JVM (Heap & Non-Heap Memory)

15 min