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