...
Because of these reasons, it is indispensable to check the condition using a loop, after wait()
is called.
Noncompliant Code Example
This noncompliant code example invokes the wait()
method inside a traditional if
block and fails to check the post condition after the notification (accidental or malicious) is received. This means that the thread can wake up when it is not supposed to.
Code Block | ||
---|---|---|
| ||
synchronized(object) { if(<condition does not hold>) object.wait(); //proceed when condition holds } |
Compliant Solution
This compliant solution encloses the wait()
method in a while
loop and as a result checks the condition during both pre and post wait()
invocation times.
...
Likewise, if the await()
method of the {java.util.concurrent.locks.Condition}} interface is implemented, it should be enclosed in a loop.
Risk Assessment
To guarantee liveness and safety, the wait()
and await()
methods should always be called inside a while
loop.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON31- J | low | unlikely | medium | P2 | L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] [Class Object|http://java.sun.com/javase/6/docs/api/java/lang/Object.html] \[[Bloch 01|AA. Java References#Bloch 01]\] Item 50: Never invoke wait outside a loop \[[Lea 00|AA. Java References#Lea 00]\] 3.2.2 Monitor Mechanics, 1.3.2 Liveness \[[Goetz 06|AA. Java References#Goetz 06]\] Section 14.2, Using Condition Queues |
...