wait/notify preconditions: calling wait() while holding the monitor but without a notifier.\n\npublic class WaitTest {\n public static void main(String[] args) {\n System.out.print("1 ");\n synchronized (args) {\n System.out.print("2 ");\n try { args.wait(); } catch (InterruptedException e) { }\n }\n System.out.print("3 ");\n }\n}

Difficulty: Easy

Correct Answer: 1 2

Explanation:


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

More Questions from Threads

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion