Thread.sleep() and Lock Release
Fast recall
Quick revision
Core answer
Classic gotcha — sleep vs wait distinction is a very common interview question
Thinking sleep releases the lock — it doesn't; Object.wait does
Contrast with Object.wait which does release the lock and must be in a synchronized block
Interview-ready guide
Interview answer
sleep pauses the current thread for a specified number of milliseconds.
sleep(2000) to sleep for two seconds. The thread moves into a timed waiting state and the CPU scheduler won't give it any time until the duration expires or the thread is interrupted. Here's the critical gotcha that interviewers love to ask: sleep does NOT release any locks the thread is holding.
If a thread enters a synchronized method, then calls sleep inside that method, it keeps the lock for the entire sleep duration. Other threads trying to enter that synchronized method will be blocked the whole time. wait, which explicitly releases the lock so other threads can acquire it.
That's why wait must be called inside a synchronized block — it needs a lock to release — but sleep can be called anywhere. You typically use sleep for simple delays in test code, like sleeping to let background threads finish before checking assertions. In production, you'd use ScheduledExecutorService instead because it's cleaner and testable.
One more thing: sleep throws InterruptedException. If another thread interrupts your sleeping thread, the exception is thrown and the sleep stops early. interrupt().
Don't just catch it and ignore it.
Thread.sleep() and Lock Release
Direct Answer
Thread.sleep pauses the current thread for the specified milliseconds. Crucially, sleep does NOT release any held locks — if a thread sleeps while holding a synchronized lock, other threads waiting for that lock remain blocked.
Common Mistakes & Pitfalls
- Thinking Sleep Releases Locks: Freshers write synchronized methods with
Thread.sleepinside, expecting other threads to acquire the lock during the sleep. They don't — the sleeping thread holds the lock the entire time. - Ignoring InterruptedException: Catching
InterruptedExceptionand doing nothing, or swallowing it. When a thread is interrupted, you should propagate the exception or restore the interrupt flag withThread.currentThread().interrupt(). - Using Sleep for Coordination: Writing while loops that sleep and check a boolean flag to wait for another thread. This is polling, which is inefficient — use wait-notify or
CompletableFutureinstead.
Check your understanding
Answer these without looking back at the article.
- What is the difference between Thread.sleep() and Object.wait()?
- Can Thread.sleep() be interrupted?
- What should you do when InterruptedException is thrown from sleep()?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.