Concurrency Początkujący

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)
);
Widzisz problem z tym kodem? Daj nam znać.
📖

Self-documenting

Duration.ofSeconds(5) is unambiguous.

🛡️

Unit-safe

No accidentally passing microseconds as milliseconds.

🧩

Composable

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

Stare podejście
Milliseconds
Nowoczesne podejście
Duration
Od JDK
19
Poziom trudności
Początkujący
Thread.sleep with Duration
Dostępne

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.

Udostępnij 𝕏 🦋 in