Inter Thread Communication in Java using wait() and notify() - Example Tutorial (original) (raw)

Wait and notify methods in Java are used for inter-thread communication i.e. if one thread wants to tell something to another thread, it uses notify() and notifyAll() method of java.lang.Object. A classical example of the wait and notify method is a Producer-Consumer design pattern, where One thread produces and put something on the shared bucket, and then tell the other thread that there is an item for your interest in a shared object, consumer thread than pick than item and do his job, without the wait() and notify(), consumer thread needs to be busy checking, even if there is no change in the state of the shared object.

This brings an interesting point on using the wait and notifies mechanism, a call to notify() happens when the thread changed state of the shared object i.e. in this case producer change bucket from empty to not empty, and consumer change state from non-empty to empty.

Also, the wait and notify method must be called from a synchronized context, wondering why to read this link for some reason which makes sense. Another important thing to keep in mind while calling them is, using a loop to check conditions instead of if block.

This is really tricky for beginners, which often don't understand difference and wonders why wait and notify get called form loops. Joshua Bloch has a very informative item in his book Effective Java, I strongly suggest reading that.

And, if you are serious about mastering Java multi-threading and concurrency then I also suggest you take a look at the Java Multithreading, Concurrency, and Performance Optimization course by Michael Pogrebinsy on Udemy. It's an advanced course to become an expert in Multithreading, concurrency, and Parallel programming in Java with a strong emphasis on high performance

In short, a waiting thread may wake up, without any change in it's waiting for the condition due to spurious wakeup.

For example, if a consumer thread, which is waiting because the shared queue is empty, gets wake up due to a false alarm and tries to get something from the queue without further checking whether the queue is empty or not then the unexpected result is possible. Here is the standard idiom for calling wait, notify, and notifyAll methods in Java :

How to call wait method in Java? Example

synchronized (object) {

while ()

object.wait();

... // Perform action appropriate to condition

}

and here is a complete example of calling the wait and notify method in Java using two threads, producer and consumer

wait notify example in Java using inter thread communication

Java Inter Thread Communication Example using wait() and notify() methods

Java inter thread communication example wait notify methodWe have a shared Queue and two threads called Producer and Consumer. Producer thread puts numbers into a shared queue and Consumer thread consumes numbers from the shared buckets.

Condition is that once an item is produced, the consumer thread has to be notified, and similarly after consumption producer thread needs to be notified. This inter-thread communication is achieved using the wait and notify method.

Remember wait and notify method is defined in the object class, and they are must be called inside the synchronized block.

package concurrency;

import java.util.LinkedList;

import java.util.Queue;

import org.apache.log4j.Logger;

public class InterThreadCommunicationExample {

public static void main(String args[]) {

final Queue sharedQ = new LinkedList();

Thread producer = new Producer(sharedQ);

Thread consumer = new Consumer(sharedQ);

producer.start();

consumer.start();

}

}

public class Producer extends Thread {

private static final Logger logger = Logger.getLogger(Producer.class);

private final Queue sharedQ;

public Producer(Queue sharedQ) {

super("Producer");

this.sharedQ = sharedQ;

}

@Override

public void run() {

for (int i = 0; i < 4; i++) {

synchronized (sharedQ) {

//waiting condition - wait until Queue is not empty

while (sharedQ.size() >= 1) {

try {

logger.debug("Queue is full, waiting");

sharedQ.wait();

} catch (InterruptedException ex) {

ex.printStackTrace();

}

}

logger.debug("producing : " + i);

sharedQ.add(i);

sharedQ.notify();

}

}

}

}

public class Consumer extends Thread {

private static final Logger logger = Logger.getLogger(Consumer.class);

private final Queue sharedQ;

public Consumer(Queue sharedQ) {

super("Consumer");

this.sharedQ = sharedQ;

}

@Override

public void run() {

while(true) {

synchronized (sharedQ) {

//waiting condition - wait until Queue is not empty

while (sharedQ.size() == 0) {

try {

logger.debug("Queue is empty, waiting");

sharedQ.wait();

} catch (InterruptedException ex) {

ex.printStackTrace();

}

}

int number = sharedQ.poll();

logger.debug("consuming : " + number );

sharedQ.notify();

//termination condition

if(number == 3){break; }

}

}

}

}

Output:

05:41:57,244 0 [Producer] DEBUG concurrency.Producer - producing : 0

05:41:57,260 16 [Producer] DEBUG concurrency.Producer - Queue is full, waiting

05:41:57,260 16 [Consumer] DEBUG concurrency.Consumer - consuming : 0

05:41:57,260 16 [Consumer] DEBUG concurrency.Consumer - Queue is empty, waiting

05:41:57,260 16 [Producer] DEBUG concurrency.Producer - producing : 1

05:41:57,260 16 [Producer] DEBUG concurrency.Producer - Queue is full, waiting

05:41:57,260 16 [Consumer] DEBUG concurrency.Consumer - consuming : 1

05:41:57,260 16 [Consumer] DEBUG concurrency.Consumer - Queue is empty, waiting

05:41:57,260 16 [Producer] DEBUG concurrency.Producer - producing : 2

05:41:57,260 16 [Producer] DEBUG concurrency.Producer - Queue is full, waiting

05:41:57,260 16 [Consumer] DEBUG concurrency.Consumer - consuming : 2

05:41:57,260 16 [Consumer] DEBUG concurrency.Consumer - Queue is empty, waiting

05:41:57,260 16 [Producer] DEBUG concurrency.Producer - producing : 3

05:41:57,276 32 [Consumer] DEBUG concurrency.Consumer - consuming : 3

That's all on this simple example of Inter thread communication in Java using the wait and notify method. You can see that both Producer and Consumer threads are communicating with each other and sharing data using shared Queue, Producer notifies consumer when there is an item ready for consumption, and Consumer thread tells Producer once it's done with consuming.

This is a classical example of the Producer-Consumer design pattern as well, which inherently involves inter-thread communication and data sharing between threads in Java.

Other Java Multithreading and Concurrency Articles you may like

Thanks for reading this article so for. If you like the Java Multithreading tutorial, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

P. S. - If you are looking for a free Java multithreading course to the master thread concepts then I also suggest you check out this Java Multithreading free course on Udemy. It's completely free and all you need is a free Udemy account to join this course.

Now, over to you, what is the best way for inter thread communication in Java? by using wait and notify method or by using Queue data structure like BlockingQueue?