rspec/rules/S2446/java/rule.adoc

66 lines
1.2 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
`notify` and `notifyAll` both wake up sleeping threads waiting on the object's monitor, but `notify` only wakes up one single thread, while `notifyAll` wakes them all up.
Unless you do not care which specific thread is woken up, `notifyAll` should be used instead.
2021-04-28 16:49:39 +02:00
=== 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
----
class MyThread implements Runnable {
Object lock = new Object();
2021-04-28 16:49:39 +02:00
@Override
public void run() {
synchronized(lock) {
2021-04-28 16:49:39 +02:00
// ...
lock.notify(); // 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
----
class MyThread implements Runnable {
Object lock = new Object();
2021-04-28 16:49:39 +02:00
@Override
public void run() {
synchronized(lock) {
2021-04-28 16:49:39 +02:00
// ...
lock.notifyAll();
2021-04-28 16:49:39 +02:00
}
}
}
----
== Resources
2021-04-28 16:49:39 +02:00
* https://wiki.sei.cmu.edu/confluence/x/MTdGBQ[CERT, THI02-J.] - Notify all waiting threads rather than a single thread
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
"notify" may not wake up the appropriate thread.
'''
== Comments And Links
(visible only on this page)
=== relates to: S3046
endif::env-github,rspecator-view[]