Java wait Method Synchronization Context
What is the primary issue with the use of the wait() method in the code segment below?
public class WaitExample {
private boolean condition = false;
public void doWait() {
if(!condition) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public void setConditionTrue() {
condition = true;
}
public static void main(String[] args) {
WaitExample we = new WaitExample();
new Thread(() -> we.doWait()).start();
}
}
A
Calling wait() outside of a synchronized context will throw an IllegalMonitorStateException at runtime.
B
The if statement should be replaced by a while loop to avoid spurious wakeups, which is the primary error.
C
There is no issue because wait() can be invoked within any method as long as it’s conditionally called.
D
The wait() method is incorrectly placed; it should be called only after the condition becomes true.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE