Inter-Thread Communication in Java – Part 1 : Free Java Tutorials

Inter-Thread Communication encompasses those Java concepts and features using which threads can communicate with each other. This communication helps to reduce the unnecessary waiting time of threads. Thus, it helps to improve overall performance.

Two threads can communicate with each other by using wait(), notify() and notifyAll() methods.

The thread which is expecting updation is responsible to call wait() method and immediately enter into the waiting state.

The thread which is responsible to perform updation will call notify() method after performing updation. At that time, waiting thread will get a notification and continue its execution with those updated items.

Impact of Inter-Thread Communication on Life Cycle of a Thread

Inter-Thread-Communication

 

The wait(), notify() and notifyAll() methods are present in Object class but not in thread class because a thread can call these methods on any Java object.

So, these methods are not entirely part of Thread class only unlike start() and join() methods.

To call wait(), notify() or notifyAll() method on any object, the thread should mandatorily own that object. That is, the thread must possess the lock of that object.

We must call the wait(), notify() and notifyAll() methods from within the synchronized block or synchronized method. Otherwise, we will get Runtime Exception saying Illegal Monitor State Exception.

If a thread calls wait() method on any object, it immediately releases the lock of that particular object and enters into the waiting state.

If a thread calls notify() method on any object, it releases the lock of that particular object but it may not release the lock immediately.

Note that when a thread calls wait(), notify() or notifyAll() method, it releases the lock of only one object on which the method is called and not the locks of all objects.

There are no other methods where thread releases the lock except wait(), notify() and notifyAll() methods.

When a thread goes into the waiting state after calling wait() method on a particular object, that thread can be interrupted by some other thread.

Hence, it is always a good practice to handle Interrupted Exception.

Since this is a checked exception, we can handle it either by using a try-catch block or by using throws keyword while calling wait method on any object.

 

Hope you find this tutorial helpful. We will see examples based on these three methods in the next tutorial.

Leave a Comment

Your email address will not be published. Required fields are marked *