Concurrency Beginner

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)
);
See a problem with this code? Let us know.
๐Ÿ“–

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)

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 โฌก