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?
-
AAfter thread A is notified, or after two seconds.
-
BAfter the lock on B is released, or after two seconds.
-
CTwo seconds after thread A is notified.
-
DTwo seconds after lock B is released.
Answer
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
waitreleases the monitor and suspends A. - Other threads may call
notify()ornotifyAll()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 callswait(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.