![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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.base/java.lang.Object.wait(Native Method) at ThreadStateTest.run(ThreadStateTest.java:4)
Advertisements