Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
hard

Java wait Method Synchronization Context

Mark
< Prev
Next >

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

There is no issue because wait() can be invoked within any method as long as it’s conditionally called.

B

The if statement should be replaced by a while loop to avoid spurious wakeups, which is the primary error.

C

The wait() method is incorrectly placed; it should be called only after the condition becomes true.

D

Calling wait() outside of a synchronized context will throw an IllegalMonitorStateException at runtime.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy|