
org.sonar.l10n.java.rules.java.S2274.html Maven / Gradle / Ivy
Why is this an issue?
In a multithreaded environment, the Object.wait(…)
, as well as Condition.await(…)
and similar methods are used to pause
the execution of a thread until the thread is awakened. A thread is typically awakened when it is notified, signaled, or interrupted, usually because
of an event in another thread requiring some subsequent action by the waiting thread.
However, a thread may be awakened despite the desired condition not being met or the desired event not having happened. This is referred to as
"spurious wakeups" and may be caused by underlying platform semantics. In other words, a thread may be awakened due to reasons that have nothing to do
with the business logic. Hence, the assumption that the desired condition is met or the desired event occurred after a thread is awakened does not
always hold.
According to the documentation of the Java Condition
interface [1]:
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 [2]:
[…] waits should always occur in loops, like this one:
synchronized (obj) {
while (<condition does not hold>){
obj.wait(timeout);
}
... // Perform action appropriate to condition
}
How to fix it
Make sure that the desired condition is actually true after being awakened. This can be accomplished by calling the wait
or
await
methods inside a loop that checks said condition.
Code examples
Noncompliant code example
synchronized (obj) {
if (!suitableCondition()){
obj.wait(timeout); // Noncompliant, the thread can be awakened even though the condition is still false
}
... // Perform some logic that is appropriate for when the condition is true
}
Compliant solution
synchronized (obj) {
while (!suitableCondition()){
obj.wait(timeout); // Compliant, the condition is checked in a loop, so the action below will only occur if the condition is true
}
... // Perform some logic that is appropriate for when the condition is true
}
Resources
- Java SE 17 & JDK 17 -
Condition
- Java Platform SE 8 - Object#wait
- CERT THI03-J. - Always invoke wait() and await() methods inside a loop