IllegalMonitorStateException
wait() method
Java exceptions
multithreading
Java programming

IllegalMonitorStateException on wait call

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

IllegalMonitorStateException on wait() Call

Understanding the IllegalMonitorStateException is crucial when dealing with multithreading in Java, particularly when working with thread synchronization using methods like wait(), notify(), and notifyAll(). This article delves into the underlying reasons for this exception, practical examples, and best practices to avoid it.

Overview

The IllegalMonitorStateException in Java is an unchecked exception that typically occurs during synchronization when a thread tries to perform an operation without holding the appropriate monitor lock. The exception specifically states that a thread is in an illegal state to call a certain monitor operation.

Common Scenario: The wait() Method

Explanation

The wait() method is used in thread communication. It makes the current thread wait until another thread calls notify() or notifyAll() on the same object. For a thread to call wait() on an object, it must hold the monitor lock of that object.

IllegalMonitorStateException Cause

The IllegalMonitorStateException is thrown if a thread attempts to call wait() on an object's monitor it does not own. Owning the monitor means the thread has synchronized on the object using a synchronized block or method.

Example

Below is an example that demonstrates the IllegalMonitorStateException in the context of a wait() call:

java
1public class MonitorExample {
2    private final Object lock = new Object();
3
4    public void incorrectWait() {
5        try {
6            // This line will throw IllegalMonitorStateException because
7            // the current thread does not hold the lock on the `lock` object.
8            lock.wait();
9        } catch (InterruptedException e) {
10            Thread.currentThread().interrupt();
11            System.out.println("Thread interrupted");
12        } catch (IllegalMonitorStateException e) {
13            System.out.println("IllegalMonitorStateException: " + e.getMessage());
14        }
15    }
16
17    public void correctWait() {
18        synchronized (lock) {
19            try {
20                // This is valid because the current thread
21                // holds the lock on the `lock` object.
22                lock.wait();
23            } catch (InterruptedException e) {
24                Thread.currentThread().interrupt();
25                System.out.println("Thread interrupted");
26            }
27        }
28    }
29}

In the incorrectWait() method, calling wait() on the lock object will throw an IllegalMonitorStateException because the current thread does not have the monitor lock on lock. In contrast, correctWait() synchronizes on lock, ensuring the current thread has the monitor before calling wait().

Just like wait(), the notify() and notifyAll() methods require the current thread to own the object's monitor. Failing to do so will result in an IllegalMonitorStateException.

Avoiding IllegalMonitorStateException

  • Synchronize properly: Always ensure that the current thread holds the monitor lock of an object before calling wait(), notify(), or notifyAll() on it.
  • Use synchronized blocks or methods: These constructs inherently acquire and release the monitor lock, preventing accidental method calls without the monitor.
  • Consistency: Ensure that wait and notify calls relate to the same lock object to avoid confusion.

Summary Table

OperationConditionException Thrown
wait()No monitor heldIllegalMonitorStateException
notify()No monitor heldIllegalMonitorStateException
notifyAll()No monitor heldIllegalMonitorStateException
Synchronized Block Synchronized MethodHolds the monitor on start and releases at endNo exception if properly used

Additional Details

  • Thread State: When a thread calls wait(), it transitions from the running to the waiting state. Once notified, it transitions back to runnable once the lock is reacquired.
  • Timeout Variants: wait(long timeout) and wait(long timeout, int nanos) are overloaded variants where a thread will wait for the specified time if not notified sooner.
  • Interrupts and Exceptions: The wait() method can throw InterruptedException, so it's essential to handle it, typically by reasserting the interrupt status.

Understanding the IllegalMonitorStateException and how to handle the wait() operation is vital for writing robust multithreaded applications in Java. By adhering to synchronization best practices, you can avoid common pitfalls and ensure efficient and safe inter-thread communication.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.