

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.lang.Object.wait(Native Method) at ThreadStateTest.run(ThreadStateTest.java:4)
- Related Questions & Answers
- How can we call the invokeLater() method in Java?
- When can we call wait() and wait(long) methods of a Thread in Java?
- Can we call methods of the superclass from a static method in java?
- Can we call a constructor directly from a method in java?
- Can we call run() method directly instead of start() in Java
- Can we execute a java program without a main method?
- Can we call Superclass’s static method from subclass in Java?
- Can we overload the main method in Java?
- Can we override the static method in Java?
- Can we override the main method in java?
- Can we override the equals() method in Java?
- Can we create a program without a main method in Java?
- Can we define an abstract class without abstract method in java?
- What will happen if we directly call the run() method in Java?
- How do we call a Java method recursively?
Advertisements