For any developer trying to learn multi-threaded programming, it is important to learn the difference between wait/notify mechanism and synchronized keyword.

Both of them are explained below:

wait/notify mechanism

wait/notify mechanism is used for inter-thread communication where one thread needs to wait until another thread completes its job.

All three wait, notify and notifyAll methods are part of Object class. Since Object class is inherited by all classes in Java, these methods become part of all objects created in Java. Another point to remember is that threads can be locked on any objects they are locked on. So any object can be used for locking a thread from further execution.

Let us understand the working of wait and notify with the help of example code:

package com.example;

public class Foo implements Runnable{

	public static Foo f =  new Foo();

	public void run() {
		if(Thread.currentThread().getName().equals("t1")) {
			System.out.println("inside test1");
			synchronized(f) {
				try {
					Thread t2 = new Thread(new Foo());
					t2.setName("t2");
					t2.start();
					f.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println("the sysout in t1");
		} else {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("inside test2");

			synchronized(f) {
				System.out.println("the sysout in t2");
				f.notifyAll();
			}	
		}
	}

	public static void main(String[] args) {
		Thread t1 = new Thread(new Foo());
		t1.setName("t1");
		t1.start();
	}
}

Output:

inside test1
inside test2
the sysout in t2
the sysout in t1

The above output shall always be seen with the above program. Had we removed wait and notify statements from the above code, the output shall vary and we can’t be sure of the ordering we have achieved with the use of wait and notify methods.

Some important points to note about wait/notify mechanism in Java:

  • The use of wait method causes the current thread to release the lock. The wait method needs to be invoked from a synchronized block guarded by using the same object on which wait method is invoked.
  • The thread which invoked the wait method shall continue to keep wait until some other thread invokes notify/notifyAll method.
  • The notifyAll method notifies all waiting threads that they can continue their processing. Whereas, the notify method notifies only one random thread waiting on the lock for which notify method has been invoked.
  • synchronized keyword

    The synchronized keyword is used to guarded mutually exclusive block code. The properties of such a piece of code is that the bunch of statements should be considered as a atomic operation. For example, auditing savings account and then withdrawing money. If these two operations are not executed in a single go then there are big chances that multiple threads shall cause issues.

    Read more on synchronized keyword and sample source code

    Salient points which differentiate wait/notify from synchronized keyword

    • The purpose of wait/notify/notifyAll is to block an operation and let other thread know that it is now his turn to start execution. Once the other thread completes the execution, it notifies the first thread that now it has done its job and first thread can continue.

      Where as synchronization is used to make sure that a piece of code should be run by a single thread at a time. There is no ordering involved in synchronization. Any thread may enter the synchronized block but it is not guaranteed which one shall enter.

    • Since all classes inherit the wait, notify and notifyAll methods from the Object class, any object can be used to invoke these methods for a thread. There is no concept of object level or class level locks. The only thing to be ensured is that the same object be used for invoking wait as well as notify/notifyAll methods.

      With synchronization, there is huge difference in the working of threads depending upon the object being used for synchronization and the object used for synchronized block/method. There is a concept of object level and class level locks with synchronized keyword in Java.

    Difference between wait/notify mechanism and synchronized admin Core Java
    For any developer trying to learn multi-threaded programming, it is important to learn the difference between wait/notify mechanism and synchronized keyword. Both of them are explained below: wait/notify mechanism wait/notify mechanism is used for inter-thread communication where one thread needs to wait until another thread completes its job. All three wait, notify and...
    For any developer trying to learn multi-threaded programming, it is important to learn the difference between wait/notify mechanism and synchronized keyword. Both of them are explained below: <h2>wait/notify mechanism</h2> wait/notify mechanism is used for inter-thread communication where one thread needs to wait until another thread completes its job. All three wait, notify and notifyAll methods are part of Object class. Since Object class is inherited by all classes in Java, these methods become part of all objects created in Java. Another point to remember is that threads can be locked on any objects they are locked on. So any object can be used for locking a thread from further execution. Let us understand the working of wait and notify with the help of example code: 1 <strong>Output:</strong> <blockquote> inside test1 inside test2 the sysout in t2 the sysout in t1 </blockquote> The above output shall always be seen with the above program. Had we removed wait and notify statements from the above code, the output shall vary and we can't be sure of the ordering we have achieved with the use of wait and notify methods. Some important points to note about wait/notify mechanism in Java: <ul> <li>The use of wait method causes the current thread to release the lock. The wait method needs to be invoked from a synchronized block guarded by using the same object on which wait method is invoked. </li> <li>The thread which invoked the wait method shall continue to keep wait until some other thread invokes notify/notifyAll method. </li> <li>The notifyAll method notifies all waiting threads that they can continue their processing. Whereas, the notify method notifies only one random thread waiting on the lock for which notify method has been invoked. </li> <h2>synchronized keyword</h2> The synchronized keyword is used to guarded mutually exclusive block code. The properties of such a piece of code is that the bunch of statements should be considered as a atomic operation. For example, auditing savings account and then withdrawing money. If these two operations are not executed in a single go then there are big chances that multiple threads shall cause issues. <a href="http://www.javaexperience.com/object-and-class-level-locks-in-java/">Read more on synchronized keyword and sample source code</a> <h2>Salient points which differentiate wait/notify from synchronized keyword</h2> <ul> <li>The purpose of wait/notify/notifyAll is to block an operation and let other thread know that it is now his turn to start execution. Once the other thread completes the execution, it notifies the first thread that now it has done its job and first thread can continue. Where as synchronization is used to make sure that a piece of code should be run by a single thread at a time. There is no ordering involved in synchronization. Any thread may enter the synchronized block but it is not guaranteed which one shall enter. </li> <li> Since all classes inherit the wait, notify and notifyAll methods from the Object class, any object can be used to invoke these methods for a thread. There is no concept of object level or class level locks. The only thing to be ensured is that the same object be used for invoking wait as well as notify/notifyAll methods. With synchronization, there is huge difference in the working of threads depending upon the object being used for synchronization and the object used for synchronized block/method. There is a concept of object level and class level locks with synchronized keyword in Java. </li> </ul>
    The following two tabs change content below.
    I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database. Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post. Thanks for the support.