Difference between notify() and notifyAll() in Java


Both notify and notifyAll are the methods of thread class and used to provide notification for the thread.But there are some significant differences between both of these methods which we would discuss below.

Following are the important differences between notify and notifyAll.

Sr. No.KeynotifynotifyAll
1NotificationIn case of multiThreading notify() method sends the notification to only one thread among the multiple waiting threads which are waiting for lock.While notifyAll() methods in the same context sends the notification to all waiting threads instead of single one thread.
2Thread identificationAs in case of notify the notification is sent to single thread among the multiple waiting threads so it is sure that which of those waiting thread is going to receive the lock.On other hand notifyAll sends notification to all waiting threads hence it is not clear which of the thread is going to receive the lock.
3Risk factorIn case of notify() method the risk of thread missing is high as notification is sent only single thread and if it misses that than no other thread would get notification and hence the lock.While in case of notifyAll as notification is to all the waiting threads and hence if any thread misses the notification, there are other threads to do the job.Hence risk is less.
4PerformanceMemory and CPU drain is less as compare to notifyAll as notification is sent to single one thread so performance is better as compare to notifyAll.On other hand as the cost of no notification is dropped and notification is sent to all waiting threads the memory and CPU drain is more as compare to notify and hence performance of notifyAll is lesser.
5InterchangeableIn case of the notify() method as only single one thread is in picture hence no concept of thread Interchangeable is possible.While we should go for notifyAll() if all your waiting threads are interchangeable (the order they wake up doesnâTMt matter).

Example of notify vs notifyAll

ThreadA.java

Example

 Live Demo

public class ThreadA {
   public static void main(String[] args){
      ThreadB b = new ThreadB();
      b.start();
      synchronized(b){
         try{
            System.out.println("Waiting for b to complete...");
            b.wait();
         }
         catch(InterruptedException e){
            e.printStackTrace();
         }
         System.out.println("Total is: " + b.total);
      }
   }
}
class ThreadB extends Thread{
   int total;
   public void run(){
      synchronized(this){
         for(int i=0; i<100 ; i++){
            total += i;
         }
         notify();
      }
   }
}

Output

Waiting for b to complete...
Total is: 4950

Updated on: 02-Mar-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements