wait/notify preconditions: calling wait() while holding the monitor but without a notifier. public class WaitTest { public static void main(String[] args) { System.out.print("1 "); synchronized (args) { System.out.print("2 "); try { args.wait(); } catch (InterruptedException e) { } } System.out.print("3 "); } }
Correct Answer: 1 2
Introduction / Context: This exercise probes correct use of Object.wait(). The thread must own the monitor of the object on which wait() is called, and typically some other thread should notify/notifyAll() to resume the waiting thread.
Given Data / Assumptions:
- The code synchronizes on args and then calls args.wait().
- No other thread exists that could call notify/notifyAll() on the same monitor.
- InterruptedException is caught properly.
Concept / Approach: The call occurs while holding the monitor, satisfying the precondition; thus no IllegalMonitorStateException is thrown. However, because no other thread notifies, the waiting thread never wakes up. Therefore the code prints “1 2” and then blocks indefinitely; “3” is never printed.
Step-by-Step Solution:
Print “1 ”.Enter synchronized(args) and print “2 ”.Call args.wait(): releases the monitor and parks the thread.No notify occurs → the program hangs.Verification / Alternative check: Adding a second thread that locks on args and invokes notify() would allow the main thread to resume and print “3”.
Why Other Options Are Wrong:
- IllegalMonitorStateException is not required to be handled and does not occur here.
- “1 2 3” and “1 3” contradict the waiting behavior.
Common Pitfalls: Forgetting to pair wait() with a proper notify path; calling wait() without holding the monitor (which would cause IllegalMonitorStateException).
Final Answer: 1 2