Java monitors: which statement about notify/notifyAll/wait and synchronization requirements is true?

Difficulty: Easy

Correct Answer: The notifyAll() method must be called from a synchronized context.

Explanation:


Introduction / Context:
This item probes your understanding of where the monitor methods wait(), notify(), and notifyAll() can legally be invoked and which classes define them. Misconceptions here cause IllegalMonitorStateException and subtle concurrency bugs.


Given Data / Assumptions:

  • Java monitors are associated with every Object instance.
  • wait(), notify(), and notifyAll() operate on an Object’s monitor, not on threads directly.
  • Correct usage requires holding the relevant monitor.


Concept / Approach:
All three methods—wait, notify, notifyAll—are instance methods of java.lang.Object and must be called by a thread that currently owns that object’s monitor (i.e., from within a synchronized block/method on that same object). Otherwise, the runtime throws IllegalMonitorStateException.


Step-by-Step Solution:
Check Option A: notifyAll() must be called while holding the object’s monitor ⇒ true (same requirement as for notify() and wait()).Option B reverses the relationship: the calling thread must own the object’s lock, not the other way around ⇒ false.Option C: notify() is in Object, not Thread ⇒ false.Option D: notify() does not release any locks immediately; the notifying thread keeps them until leaving the synchronized block ⇒ false.


Verification / Alternative check:
Call notifyAll() outside synchronized; you will see IllegalMonitorStateException. Wrap it in synchronized(obj) { obj.notifyAll(); } and it works.


Why Other Options Are Wrong:
They either misstate ownership rules, attribute methods to the wrong class, or misdescribe lock-release timing.


Common Pitfalls:
Calling notify()/wait() on the wrong object; assuming notify() “hands off” the lock immediately; forgetting that these are Object methods.


Final Answer:
The notifyAll() method must be called from a synchronized context.

Discussion & Comments

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