Concurrency beginner

Thread.sleep with Duration

Use Duration for self-documenting time values.

✕ Java 8
// What unit is 5000? ms? us?
Thread.sleep(5000);

// 2.5 seconds: math required
Thread.sleep(2500);
✓ Java 19+
Thread.sleep(
    Duration.ofSeconds(5)
);
Thread.sleep(
    Duration.ofMillis(2500)
);
📖

Self-documenting

Duration.ofSeconds(5) is unambiguous.

🛡️

Unit-safe

No accidentally passing microseconds as milliseconds.

🧩

Composable

Duration math: plus(), multipliedBy(), etc.

Old Approach
Milliseconds
Modern Approach
Duration
Since JDK
19
Difficulty
beginner
Thread.sleep with Duration
Available

Widely available since JDK 19 (Sept 2022)

How it works

Thread.sleep(Duration) makes the time unit explicit. No more guessing whether 5000 means milliseconds or microseconds. Works with Duration.ofSeconds, ofMillis, ofMinutes, etc.

Share 𝕏 🦋 in