2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-06-08 15:55:22 +02:00
`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
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-08 15:55:22 +02:00
[source,java,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
2023-06-08 15:55:22 +02:00
class MyThread implements Runnable {
Object lock = new Object();
2021-04-28 16:49:39 +02:00
@Override
2023-06-08 15:55:22 +02:00
public void run() {
synchronized(lock) {
2021-04-28 16:49:39 +02:00
// ...
2023-06-08 15:55:22 +02:00
lock.notify(); // Noncompliant
2021-04-28 16:49:39 +02:00
}
}
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2023-06-08 15:55:22 +02:00
[source,java,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
2023-06-08 15:55:22 +02:00
class MyThread implements Runnable {
Object lock = new Object();
2021-04-28 16:49:39 +02:00
@Override
2023-06-08 15:55:22 +02:00
public void run() {
synchronized(lock) {
2021-04-28 16:49:39 +02:00
// ...
2023-06-08 15:55:22 +02:00
lock.notifyAll();
2021-04-28 16:49:39 +02:00
}
}
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +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
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
"notify" may not wake up the appropriate thread.
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== relates to: S3046
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]