Member-only story

Java Multithreading, Concurrency, and Parallelism — Part 10

KRISHNA KISHORE V

--

The Interthread Communication — wait, notify and notifyall

In Part-9 we have seen various scenarios where threads can get blocked on each other. In this part, we will see how can threads voluntarily leave the monitor and go into the WAITING state and resume — wait(), notify() & notifyall().

Purpose of wait and notify: A common pattern in multi-threaded programming is to have some kind of communication between the threads. So the wait and notify are more of a communication mechanism. This mechanism allows one thread to communicate to another that a particular condition or event has occurred. And the wait & notify mechanism won’t tell us what is that particular condition/event. That is where the Shared Object comes into the picture.

The most important thing to remember is that, the wait & notify mechanism doesn’t replace the behavior ofsynchronized keyword as it cannot alone solve the race condition problem that the synchronized solves. In fact, the wait & notify mechanism must be used in conjunction with the synchronized to prevent a race condition.

The wait & notify mechanism must be used in conjunction with synchronized.

To understand the wait & notify let's look at a single producer and a single consumer problem — which is simply known as the producer-consumer problem.

The producer-consumer problem is very simple. It can be better understood with a real-world example.

--

--

KRISHNA KISHORE V
KRISHNA KISHORE V

Written by KRISHNA KISHORE V

Full Stack Tech Lead | Software Consultant | Technical Content Writer

Responses (1)

Write a response