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

JavaObject Oriented ProgrammingProgramming

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.lang.Object.wait(Native Method)
at ThreadStateTest.run(ThreadStateTest.java:4)
raja
Published on 26-Aug-2019 14:30:58
Advertisements