rspec/rules/S2274/java/rule.adoc

68 lines
1.6 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
According to the documentation of the Java ``++Condition++`` interface:
____
When waiting upon a ``++Condition++``, a "spurious wakeup" is permitted to occur, in general, as a concession to the underlying platform semantics. This has little practical impact on most application programs as a Condition should always be waited upon in a loop, testing the state predicate that is being waited for. An implementation is free to remove the possibility of spurious wakeups but it is recommended that applications programmers always assume that they can occur and so always wait in a loop.
____
The same advice is also found for the ``++Object.wait(...)++`` method:
____
waits should always occur in loops, like this one:
----
synchronized (obj) {
while (<condition does not hold>){
obj.wait(timeout);
}
... // Perform action appropriate to condition
}
----
____
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
synchronized (obj) {
if (!suitableCondition()){
obj.wait(timeout); //the thread can wake up even if the condition is still false
}
... // Perform action appropriate to condition
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
synchronized (obj) {
while (!suitableCondition()){
obj.wait(timeout);
}
... // Perform action appropriate to condition
}
----
== Resources
2021-04-28 16:49:39 +02:00
* https://wiki.sei.cmu.edu/confluence/x/EzdGBQ[CERT THI03-J.] - Always invoke wait() and await() methods inside a loop
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove this call to "xxx" or move it into a "while" loop.
endif::env-github,rspecator-view[]