Java concurrency: A thread A calls wait(2000) inside a synchronized method on object B. When does thread A become eligible (a candidate) to run again?

Difficulty: Medium

Correct Answer: After thread A is notified, or after two seconds.

Explanation:


Introduction / Context:
Timed waiting with wait(timeout) is a core synchronization mechanism in Java. Knowing precisely when a waiting thread can proceed is key to designing correct monitors.



Given Data / Assumptions:

  • Thread A executed wait(2000) while holding B’s monitor (inside synchronized code on B).
  • Calling wait releases the monitor and suspends A.
  • Other threads may call notify() or notifyAll() on B.


Concept / Approach:
With wait(timeout), a thread stops waiting when either it is notified or the timeout elapses. After that, it must re-acquire B’s monitor before resuming running. The question asks when it becomes a candidate for CPU time, which is upon notification or timeout expiration.



Step-by-Step Solution:

1) A calls wait(2000) → releases monitor B and enters TIMED_WAITING.2) Either another thread calls notify/notifyAll on B, or 2 seconds pass.3) A transitions to BLOCKED (contending for B’s monitor) and, once it re-acquires B’s monitor, can run again.


Verification / Alternative check:
Even after notification/timeout, progress depends on re-acquiring B’s lock; however, eligibility begins at notify/timeout boundaries.



Why Other Options Are Wrong:

  • Option B over-emphasizes lock release as the trigger; the primary triggers are notify or timeout.
  • Options C and D misstate sequencing and conditions.


Common Pitfalls:
Confusing “eligible to run” with “actively running.” Lock reacquisition is still required after notify/timeout.



Final Answer:
After thread A is notified, or after two seconds.

More Questions from Threads

Discussion & Comments

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