Can we call the wait() method without acquiring the lock in Java?


No, we cannot call the wait() method without acquiring the lock. In Java, once the lock has been acquired then we need to call wait() method (with timeout or without timeout) on that object. If we are trying to call the wait() method without acquiring a lock, it can throw java.lang.IllegalMonitorStateException.

Example

public class ThreadStateTest extends Thread {
   public void run() {
      try {
         wait(1000);
      } catch(InterruptedException ie) {
         ie.printStackTrace();
      }
   }
   public static void main(String[] s) {
      ThreadStateTest test = new ThreadStateTest();
      test.start();
   }
}

In the above example, we need to call wait() method without acquiring the lock so it generates an IllegalMonitorStateException at the runtime. In order to fix the issue, we need to acquire the lock before calling the wait() method and declare the run() method synchronized.

Output

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
	at java.base/java.lang.Object.wait(Native Method)
	at ThreadStateTest.run(ThreadStateTest.java:4)

Updated on: 27-Nov-2023

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements