org.sonar.l10n.java.rules.squid.S2274.html Maven / Gradle / Ivy
According to the Java Condition
interface documentation:
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
synchronized (obj) {
if (!suitableCondition()){
obj.wait(timeout); //the thread can wakeup whereas the condition is still false
}
... // Perform action appropriate to condition
}
Compliant Solution
synchronized (obj) {
while (!suitableCondition()){
obj.wait(timeout);
}
... // Perform action appropriate to condition
}
See
- CERT THI03-J - Always invoke wait() and await() methods inside a loop
© 2015 - 2025 Weber Informatics LLC | Privacy Policy