Difficulty: Easy
Correct Answer: An exception occurs at runtime
Explanation:
Introduction / Context:
Object.wait() and Object.notify()/notifyAll() must be invoked by a thread that currently owns the object’s monitor; otherwise, the JVM throws IllegalMonitorStateException. This example intentionally calls wait/notify without synchronization to test your understanding of this precondition.
Given Data / Assumptions:
Concept / Approach:
Because neither doStuff() nor its caller holds Foo’s monitor (i.e., synchronized(this)), calling wait() immediately raises IllegalMonitorStateException at runtime. Likewise, notify() would also be illegal if reached. Proper usage requires doStuff() to be synchronized or to wrap wait/notify inside synchronized(this) {}.
Step-by-Step Solution:
Verification / Alternative check:
Fix by declaring public synchronized void doStuff() and by using a condition loop (while (x < 10) wait();), then notify() inside the synchronized context when the condition changes.
Why Other Options Are Wrong:
Common Pitfalls:
Forgetting to synchronize when using wait/notify; using if instead of while around wait, which can lead to spurious wakeup issues.
Final Answer:
An exception occurs at runtime
Discussion & Comments