Java/J2EE and SOA (305 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (45 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (304 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

What is Wait and Notify in Java?

Published on Sep 17,2019 91 Views
47 / 72 Blog from Java Core Concepts

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

Multithreading feature in Java allows concurrent execution of two or more parts of a program. Each part is a Thread. These threads often have to coordinate their actions. This is done using a few final methods like Wait and Notify in Java. This article will help you understand these methods in detail.

I’ll be discussing the topics in the following order:

Let’s begin!

What is Thread Synchronization?

Multi-threaded programs may regularly come up with a situation where multiple Java threads attempt to get to the same resource which produces fraudulent and startling outcomes. At times, more than one thread might try to access a shared resource, you need to ensure that resource will be used by only one thread at a time. This can be done using Synchronization in Java. 

Now talking about Polling. Polling is a process of testing a condition repeatedly until it is true. This method is implemented with the help of loops to check whether a particular condition is true or not. You can use this method for threads but this method wastes a lot of CPU cycles and also makes the implementation process very inefficient. To avoid these kinds of bugs, methods like Wait and Notify in Java are introduced.

What are Wait () and Notify() methods?

To tackle the multithreading problem, methods like Wait and Notify in Java are used. The Object class uses these three final methods that allow threads to communicate about the locked status of a resource. They are also termed as the Guarded Blocks.

Wait()

This method causes the thread to wait until another thread invokes notify() and notifyAll() methods for this object. This Wait() method tells the calling thread to let go of a lock and go to sleep until some other thread enters the same monitor and calls to notify(). This method releases the lock before waiting and reacquires the lock before returning from the wait() method.

Wait() method is tightly integrated with the synchronization lock. This is done by using a feature not available directly from the synchronization mechanism.

Syntax:

synchronized( lockObject )
{
while( ! condition )
{
lockObject.wait();
}
//take the action here;
}

The current thread must own it’s object’s monitor. It must be called from the synchronized method only or else it will throw an exception.

Notify()

This method is used to notify the threads that it needs to function. It wakes up one thread that called the wait() method on the same object.

Note that calling notify() eventually does not give up a lock. It tells a waiting thread that it can wake up. However, the lock is not actually given up until the notifier’s synchronized block has completed. Now say, if you call notify() on a resource but the notifier still needs to perform actions for 10 seconds within its synchronized block, the thread that had been waiting will have to wait at least for another additional 10 seconds for the notifier to release the lock on the object, even though notify() had been called.

Syntax:

synchronized(lockObject)
{
//establish_the_condition;
lockObject.notify();
//any additional code if needed
}

NotifyAll()

This method is used to wake all the threads up that had called wait() on the same object. The highest priority thread will first run in most of the situation even though it is not guaranteed. Other things are the same as notify() method.

Why and how to use Wait() and Notify() in Java?

You should use Wait and Notify in Java because they are related to lock and object has a lock. Even though wait and notify in Java are quite a fundamental concept, they are defined in the object class.  Surprisingly, it’s not that easy to write the code using wait and notify. You can test this by writing code to solve the producer-consumer problem using wait and notify.Producer consumer example-Wait and Notify in Java-EdurekaHere, I have a shared Queue and two threads called Producer and Consumer. Producer thread puts the number into a shared queue and Consumer thread consumes the numbers from the shared bucket.

 

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

Note: Wait and Notify methods are defined in the object class, and they must be called inside synchronized block. 

Example

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

Notice that in the above example, an object of Thread2, that is b, is synchronized. This b completes the calculation before the Main thread outputs its total value.

Output:

Output- Wait and Notify in Java-Edureka

This brings us to the end of this article where we have learned the frequently asked questions on the Wait and Notify in Java. I hope the above-mentioned content proved to be helpful in enhancing your Java knowledge. Keep reading, keep exploring!

Also check out Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.