Course contentsShow
← Java
Lesson 2596 of 2,87048. Concurrency FundamentalsFree lesson

Sleep Precision and Guarantees

Understanding that sleep duration is a minimum guarantee, not exact timing promise.

Sleep Precision and Guarantees

What you'll learn: You'll understand why Thread.sleep() provides a minimum wait time, not an exact, precise delay.

When you call Thread.sleep(1000), you're asking the JVM to pause your thread for at least 1000 milliseconds—but that's not a hard promise of exactly one second. It's a guarantee of a minimum duration, not precision timing.

Why Sleep Isn't Precise

The JVM and operating system work together to schedule threads. When your thread sleeps, it enters the TIMED_WAITING state and yields CPU time to other threads. Once the sleep duration expires, your thread becomes eligible to run again (moves to RUNNABLE)—but it doesn't necessarily execute immediately.

Think of it like this: You set an alarm for 7:00 AM. The alarm guarantees you won't wake up before 7:00 AM, but it doesn't guarantee you'll jump out of bed at exactly 7:00:00.000. You might hit snooze, or take a moment to stretch. Similarly, your thread might wait a few extra milliseconds (or more) for the scheduler to grant it CPU time.

Factors Affecting Actual Sleep Duration

  • System load: Heavy CPU usage means more threads competing for execution time
  • Scheduler granularity: Operating systems often schedule in time slices (e.g., 10-15ms chunks)
  • JVM overhead: The runtime itself adds small delays
  • Platform differences: Windows, Linux, and macOS have different scheduler behaviors
long start = System.currentTimeMillis();
Thread.sleep(100); // Request 100ms minimum
long actualDuration = System.currentTimeMillis() - start;
// actualDuration might be 101, 105, 115ms... never less than 100

Key Takeaway: Thread.sleep() guarantees your thread will sleep for at least the specified duration, but never use it for precise timing—actual wake-up time depends on the thread scheduler and system conditions.