Here we will discuss the wait() method in Java. It is the most common question in interviews.
Here is the table content of the article will we will cover this topic.
1. What is the wait() method in Java?
2. How does the wait() method works?
3. wait(long timeoutMillis) method?
What is the wait() method in Java?
The wait() method is defined in the Object class which is the super most class in Java. This method tells the calling thread (Current thread) to give up the lock and go to sleep until some other thread enters the same monitor and calls notify() or notifyAll(). It is a final method, so we can’t override it.
Let’s have a look at the code.
public final void wait() throws InterruptedException { wait(0L); }
How wait() method works?
1. The wait() method is used for interthread communication. In Inter-thread communication, the synchronized threads can communicate with each other. As you know in a synchronized block or method, only one thread can enter(acquire the lock). By use of the wait() method a thread is paused(release lock) running in its critical section and another thread can enter (acquire the lock) in the same critical section.
So that multiple threads can communicate between the thread by use of use wait() and notify(). You can tell one thread to stop working (By the wait() method) from another thread based upon some condition, later you can notify it to start processing again(By notify() or notifyAll() method).
2. The wait() method is tightly integrated with the synchronization lock, using a feature not available directly from the synchronization mechanism.
3. Unlike the sleep() method, in the wait() method, the thread goes into waiting state and it won’t come back automatically until we call the notify() or notifyAll().
Let’s understand with an example
Let’s say a user wants to print some pages in the printer. So, we are creating two threads, one thread for printing the pages and another thread for adding the pages to the printer.
If the number of papers in the printer is less than the number of entered inputs, then we will call the wait() method for the thread, meanwhile, another thread will add more pages in the printer and notify the current thread by notify() method.
class Printer { // Initial 100 paper are set in Printer int noOfPaper = 100; // Synchronized the method for inter-thread communication synchronized void printingPages(int pages) { System.out.println("Printing the Pages"); for(int i = 0; i < 100; i++) { // Printing Pages } // If balance number of Papers are less than user input // then wait for addPages() synchronized method // and printing will resume after that if (this.noOfPaper < pages) { System.out.println("Number of Papers in printer are less"); try { System.out.println("Waiting..."); wait(); } catch (Exception e) { } } System.out.println("After called notify() method number of Paper : " + this.noOfPaper); System.out.println("Printing process complete"); } synchronized void addPages(int noOfPages) { // Adding more Papers in Printer; this.noOfPaper += noOfPages; // After adding the paper in printer. Notify the Paused thread; notify(); } } public class MainClass { public static void main(String args[]) { Printer printer = new Printer(); // create two new thread and start them simultaneously //First thread for print the pages new Thread() { @Override public void run() { // User want to print 120 pages printer.printingPages(120); } }.start(); // Second thread for Add pages in printer new Thread() { @Override public void run() { // Add 100 more pages in Printer printer.addPages(100); } }.start(); } }
Output: Printing the Pages
Number of Papers in printer are less
Waiting…
After called notify() method number of Paper : 200
Printing process complete
Object class has three variances of the wait() method. We will discuss them one by one.
1. wait() method: This method doesn’t take any argument; it waits indefinitely for any other thread to call notify() or notifyAll() method on the object to wake up the current thread. We discussed this method in the above example.
2. wait(long timeoutMillis) method: The other two variances put the current thread in wait for a specific amount of time before they wake up.
wait(long timeoutMillis) method
It is another variance of the wait() method. By use of this method the calling thread (Current thread) gives up the lock and goes to sleep until a certain amount of time has elapsed or calls notify() or notifyAll().
public final native void wait(long timeoutMillis) throws InterruptedException;
Here timeoutMillis the maximum time to wait, in milliseconds. You can’t send the negative value as a parameter.
Using a negative value then the compiler throws IllegalArgumentException.
If the current thread is not the owner of the object’s monitor then the compiler throws IllegalMonitorStateException.
If any thread interrupted the current thread before or while the current thread was waiting. then the compiler throws InterruptedException.
class Printer { // Initial 100 paper are set in Printer int noOfPaper = 100; // Synchronized the method for inter-thread communication synchronized void printingPages(int pages) { System.out.println("Printing the Pages"); for(int i = 0; i < 100; i++) { // Printing Pages } // If balance number of Papers are less than user input // then wait for addPages() synchronized method // and printing will resume after that if (this.noOfPaper < pages) { System.out.println("Number of Papers in printer are less"); try { System.out.println("Waiting for 5 Second..."); wait(5000); } catch (Exception e) { } } System.out.println("After called notify() method number of Paper : " + this.noOfPaper); System.out.println("Printing process complete"); } synchronized void addPages(int noOfPages) { // Adding more Papers in Printer; this.noOfPaper += noOfPages; // After adding the paper in printer. Notify the Paused thread; notify(); } } public class MainClass { public static void main(String args[]) { Printer printer = new Printer(); // create two new thread and start them simultaneously // First thread for print the pages new Thread() { @Override public void run() { // User want to print 120 pages printer.printingPages(120); } }.start(); // Second thread for Add pages in printer new Thread() { @Override public void run() { // Add 100 more pages in Printer try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } printer.addPages(100); } }.start(); } }
Output: Printing the Pages
Number of Papers in printer are less
Waiting for 5 Second…
After called notify() method number of Paper : 100
Printing process complete
Difference between wait and sleep in java
Defined in different classes
The sleep() method is defined in the Thread class and it is a static method so we can call it by Thread class.
The wait() method exists in the Object class and it is a non-static method so we can call it by the object.
Context
The wait() method is called only from the synchronized context that is synchronized block or synchronized method.
The sleep() method can be called from any context.
Call
As we discuss the wait() method is defined in the Object class. So, it operates on an Object and we can call the wait() method only by the thread object which we want to make wait.
A sleep() method operates on the current thread and when we call the sleep() method, the JVM assumes we want to sleep the thread in which the method is placed.
State change
When we use the sleep() method, it pauses the execution of the current thread and moves that thread to the TIMED_WAITING state. After the competition of waiting time, the thread moves again in a RUNNABLE state.
Where wait() method also pauses the execution of the thread and moves that thread to the WAITING state.
Lock
The sleep() method doesn’t release the lock on an object and it holds the lock for a specific time or until interrupted.
The wait() method releases the lock on an object and gives another thread a chance to acquire the lock and enter a synchronized method or block.
Wake up
When a thread is paused, it is in the TIMED_WAITING state after calling the sleep() method. It can’t be woken up. It wakes up when the given time expires. If any thread interrupts in between it throws InterruptedException.
When a thread is paused, it is in a WAITING state after calling the wait() method. it can be woken up by other threads by calling notify() or notifyAll() methods on the same lock.
Method available
The sleep() method is available in the Thread class only. We can use the sleep() method by use of the Thread class or we can extend the Thread class in our own class.
The wait() method is available in the Object class. It means, the wait() method is available in all classes. We can call it by use of the object of the class.
Execution
If we call the sleep() method by use of the thread object it will pause the current thread, not the thread that is used to call. Suppose we are calling thread1.sleep(), some programmers misunderstood the concept. It will also pause the current thread.
In each class wait() method is available, so the object has each wait() method for inter-communication between threads.
Exception
The sleep() method throws InterruptedException if any thread has interrupted the current thread and IllegalArgumentException if the value of arguments is negative.
The wait() method throws an exception If the current thread is not the owner of the object’s monitor then the compiler throws IllegalMonitorStateException.
If any thread interrupted the current thread before or while the current thread was waiting. then the compiler throws InterruptedException.
I got what you intend, saved to my bookmarks , very decent website .
Thanks very nice blog!
Please, can you PM me and tell me few more thinks about this, I am really fan of your bloggets solved properly asap.
Valuable info. Lucky me I found your website by accident, and Im shocked why this accident didnt happened earlier! I bookmarked it.
Wonderful, what a blog it is! This website
gives valuable facts to us, keep it up.
I admire what you have done here. I like the part where you say you are doing this to give back but I would assume by all the opinions that this is working for you as well.
this is best website for java I have studied from .thank you for such an informative website and easy to understand explanations
Good Site for Java Learning.