"IllegalMonitorStateException" Should Not Be Caught
What is it?
This practice is triggered by catching IllegalMonitorStateException
, which occurs when monitor operations are performed without proper ownership, indicating a programming error.
Why apply it?
Catching and handling IllegalMonitorStateException
obscures programming errors related to synchronization, potentially leading to unpredictable behavior and faulty concurrent code.
How to fix it?
Ensure that monitor operations like wait()
, notify()
, or notifyAll()
are executed within synchronized blocks, thus preventing this exception from being thrown.
Examples
Example 1:
Negative
The negative example attempts to catch IllegalMonitorStateException
instead of using synchronization, masking the underlying issue.
public class Task {
private final Object lock = new Object();
public void faultyTask() {
try {
lock.notify(); // Noncompliant
} catch (IllegalMonitorStateException e) {
// Ignoring exception
}
}
}
Example 2:
Positive
The positive example correctly uses a synchronized block to notify a thread, preventing IllegalMonitorStateException
.
public class Task {
private final Object lock = new Object();
public void doTask() {
synchronized (lock) {
lock.notify(); // Compliant
}
}
}
Negative
The negative example attempts to call notifyAll()
without proper synchronization and then catches the resulting IllegalMonitorStateException.
public class Notifier {
private final Object resource = new Object();
public void faultyNotifyAll() {
try {
resource.notifyAll(); // Noncompliant
} catch (IllegalMonitorStateException e) {
// Exception unnecessarily caught
}
}
}
Example 3:
Positive
The positive example ensures that notifyAll()
is called within synchronized block, preventing unintended exceptions.
public class Notifier {
private final Object resource = new Object();
public void notifyAllTasks() {
synchronized (resource) {
resource.notifyAll(); // Compliant
}
}
}