rspec/rules/S2235/java/rule.adoc

52 lines
1.6 KiB
Plaintext
Raw Normal View History

== 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.
2021-04-28 16:49:39 +02:00
`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.
2021-04-28 16:49:39 +02:00
Catching and handling this exception can mask underlying synchronization issues and lead to unpredictable behavior.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
[source,java,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
public void doSomething() {
2021-04-28 16:49:39 +02:00
try {
anObject.notify();
} catch(IllegalMonitorStateException e) { // Noncompliant
2021-04-28 16:49:39 +02:00
}
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
[source,java,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
public void doSomething() {
2021-04-28 16:49:39 +02:00
synchronized(anObject) {
anObject.notify();
}
}
----
== Resources
* https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/IllegalMonitorStateException.html[Oracle Java SE - IllegalMonitorStateException]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Refactor this code to not catch IllegalMonitorStateException.
endif::env-github,rspecator-view[]