Multithreading Java and Interviews Part 3: Wait and Notify All
The second installment to multithreading and interviews. Here, read an introduction to Notion of Wait and NotifyAll synchronization.
Join the DZone community and get the full member experience.Join For Free
In my previous article, we learned how to use Wait and Notify methods in order to create a thread-safe blocking Queue. But in the described example we had only 1 consumer (John thread) and 1 producer (Peter thread). In this part, we consider another example with 2 consumers and 1 producer. The main purpose of this part is to learn to notify all functions and how Java Monitor handles this scenario.
Wait and NotifyAll Detailed Explanation
Let Me Introduce Three Main Thread
Participants: John1, John 2 (consumers), and Peter (producer)
In our implementation, we have three threads. Two threads will start and try to get the data from the queue. As long as the queue is empty both of them will wait until producer thread Peter pushes 2 records inside the queue.
Now Let's Describe in Detail Each Thread Step Execution
But first, take a look into implementation. It's almost the same as in the previous article with only one difference — now the producer adds 2 records in one call.
John1 and John2 try to pool the data but got blocked due to an empty queue.
Please keep in mind that there is no guarantee that John1 will acquire MUTEX first; John2 thread has good changes to acquire mutex before John1. The description on the right side explains the current location of each thread and its status.
So the first act is done. Now we have 2 threads in the WAITING state. After 1 second we start Peter's thread. This producer thread will add 2 new records in the queue and execute Notify All method to wake up 2 waiting threads.
Now both consumers (John1, John2) are BLOCKED and the next moment one of them (random one) will acquire the mutex.
So now the process is ended and both john thread consumers are finished. I hope these stages describe the process of waiting/blocking/notifying in detail.
Opinions expressed by DZone contributors are their own.