Threads and lifecycle question 10 of 180 junior
Two threads, one Thread.sleep(1000) inside a synchronized block. What does the other thread see?
- It enters the block, sleep releases the monitor
- Correct: It stays BLOCKED for the full second, because
sleepdoes not release the monitor - It throws
IllegalMonitorStateException - It gets the lock after 500 ms because of fairness
sleep suspends the thread and keeps every lock it holds. Object.wait() is the one that releases
the monitor it was called on, and reacquires it before returning, which is precisely why wait must
be called while holding that monitor and sleep may be called anywhere.
This is the mechanism behind a whole family of production incidents: an I/O call with a long timeout
inside a synchronized block. Nothing is deadlocked, nothing is a race, and the service still stops
responding because a hundred threads are queued behind one slow monitor.