| preferred AP College board partner for AP classes
hard
Java wait Method Synchronization Context
< 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

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.

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.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

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