org.sonar.l10n.java.rules.java.S2235.html Maven / Gradle / Ivy
Why is this an issue?
The IllegalMonitorStateException
is an exception that occurs when a thread tries to perform an operation on an object’s monitor that
it does not own. This exception is typically thrown when a method like wait()
, notify()
, or notifyAll()
is
called outside a synchronized block or method.
IllegalMonitorStateException
is specifically designed to be an unchecked exception to point out a programming mistake. This exception
serves as a reminder for developers to rectify their code by correctly acquiring and releasing locks using synchronized blocks or methods. It also
emphasizes the importance of calling monitor-related methods on the appropriate objects to ensure proper synchronization.
Catching and handling this exception can mask underlying synchronization issues and lead to unpredictable behavior.
Noncompliant code example
public void doSomething() {
try {
anObject.notify();
} catch(IllegalMonitorStateException e) { // Noncompliant
}
}
Compliant solution
public void doSomething() {
synchronized(anObject) {
anObject.notify();
}
}
Resources