Quiz: Thread.sleep() in Java: How to Pause a Thread
Study the lesson first: Thread.sleep() in Java: How to Pause a Thread
Total: 6 questions
1. What overloads does Thread.sleep() have, and what other ways are there to pause in Java?
What overloads does Thread.sleep() have, and what other ways are there to pause in Java?
Thread.sleep() has three static overloads, and all of them throw InterruptedException:
sleep(long millis)- a pause in milliseconds; a negative value causesIllegalArgumentException;sleep(long millis, int nanos)- milliseconds plus nanoseconds (0-999999), with no real nanosecond precision;sleep(Duration duration)- since Java 19, for exampleThread.sleep(Duration.ofSeconds(2)).
Another popular way is TimeUnit.SECONDS.sleep(1), TimeUnit.MILLISECONDS.sleep(250) and so on: it calls the same Thread.sleep() under the hood, and a value <= 0 simply gives no pause. The Duration and TimeUnit forms are easier to read than a "magic" Thread.sleep(300000). Java has no System.sleep() or time.sleep().
2. Why does Thread.sleep() require handling InterruptedException, and how do you handle it correctly?
Why does Thread.sleep() require handling InterruptedException, and how do you handle it correctly?
InterruptedException is a checked exception: sleep() throws it when another thread calls interrupt() on the sleeping thread. So the call must be wrapped in try/catch or the method must declare throws InterruptedException; inside run() of a Runnable the second option is not possible.
When it throws, sleep() clears the interrupt flag. An empty catch or just e.printStackTrace() swallows the request to stop. The correct options are:
- if the method can, rethrow the exception (
throws InterruptedException); - otherwise restore the flag with
Thread.currentThread().interrupt()and finish the work; - when wrapping it in an unchecked exception, restore the flag first, then
throw new RuntimeException(e).
3. How accurate is the Thread.sleep() pause, and what does Thread.sleep(0) do?
How accurate is the Thread.sleep() pause, and what does Thread.sleep(0) do?
Accuracy is not guaranteed: the pause depends on system timers and the OS scheduler. Unless interrupted, a thread never wakes up early, but it can wake up noticeably late - after waking up it becomes RUNNABLE and still has to wait for a CPU. That is why Thread.sleep(1000) in a loop does not give exactly 60 iterations per minute; for a steady rhythm, use scheduleAtFixedRate().
Thread.sleep(0) does not pause: it is a hint to the scheduler, close to Thread.yield(), and its behavior depends on the JVM and OS. But if the interrupt flag is already set, even sleep(0) throws InterruptedException.
4. What is the difference between Thread.sleep() and Object.wait()?
What is the difference between Thread.sleep() and Object.wait()?
sleep() simply pauses for a given time and keeps the monitor, while wait() waits for a signal from another thread and releases the object's monitor while waiting.
sleep()is a static method ofThreadand can be called anywhere;wait()is an instance method ofObjectand can only be called insidesynchronizedon that object, otherwise you getIllegalMonitorStateException.sleep()ends when the time is up or oninterrupt();wait()ends onnotify()/notifyAll(), when thewait(ms)timeout expires, oninterrupt(), or on a spurious wakeup.- State:
TIMED_WAITINGduringsleep(),WAITINGorTIMED_WAITINGduringwait().
Use sleep() for a pause of known length and wait() to wait for an event from another thread.
5. Why is Thread.sleep() in a loop a bad way to wait for an event, and what should you use instead?
while (!dataReady) {
Thread.sleep(100);
}
process();
Why is Thread.sleep() in a loop a bad way to wait for an event, and what should you use instead?
while (!dataReady) {
Thread.sleep(100);
}
process();This kind of polling has three problems: the reaction lags by up to 100 ms; if you shorten the pause, the thread wakes up for nothing more often; and if dataReady is not volatile and not guarded by synchronization, the thread is allowed to never see the true written by another thread. IntelliJ IDEA flags such code with the inspection "Call to 'Thread.sleep()' in a loop, probably busy-waiting".
Use instead:
- to wait for a thread to finish -
t.join(); - to wait for a signal -
wait()/notify()orCountDownLatch; - to run a task periodically or after a delay -
ScheduledExecutorService(schedule(),scheduleAtFixedRate(),scheduleWithFixedDelay()).
sleep() in a loop is fine for retries with a pause between attempts, but not for waiting on an event.
6. How does Thread.sleep() work in Java 21 virtual threads?
How does Thread.sleep() work in Java 21 virtual threads?
In a virtual thread (Java 21+), Thread.sleep() does not block an OS thread: the virtual thread is unmounted from its carrier thread, and the carrier runs other virtual threads while the first one sleeps. That is why thousands of sleeping virtual threads are cheap, while thousands of platform threads calling sleep() are not.
A version detail: in Java 21-23, a virtual thread that sleeps inside synchronized gets pinned to its carrier thread and blocks it for the whole sleep. Java 24 fixed this (JEP 491), but the monitor is still held during the sleep, so pauses are better moved outside synchronized.