Thread Sleep Duration Interrupt Latency

Thread.sleep(Duration) sleeps a JDK-19 style span: negative durations are a silent no-op, and interruption throws InterruptedException after clearing the flag.

JavaResilience

Code

snippet
import java.time.Duration;

public class SleepLatency {

    static long timedSleep(Duration span) throws InterruptedException {
        long start = System.nanoTime();
        Thread.sleep(span);
        return (System.nanoTime() - start) / 1_000_000;
    }

    public static void main(String[] args) throws InterruptedException {
        // 常规睡眠:Duration 语义(JDK 19+),休眠至少给定时长
        System.out.println("slept ms: " + timedSleep(Duration.ofMillis(60)));

        // 负时长是静默 no-op:不抛异常、立即返回
        System.out.println("negative is no-op: "
                + timedSleep(Duration.ofMillis(-100)) + " ms");

        // 中断:状态被清除后抛 InterruptedException
        Thread worker = new Thread(() -> {
            try {
                Thread.sleep(Duration.ofSeconds(30));
            } catch (InterruptedException e) {
                // 异常抛出时中断标志已被清除,isInterrupted() 是 false
                System.out.println("interrupted, flag cleared: "
                        + Thread.currentThread().isInterrupted());
            }
        });
        worker.start();
        Thread.sleep(Duration.ofMillis(50));
        worker.interrupt();
        worker.join();
    }
}

Inside the snippet

Under the hood: the class SleepLatency.

Watch out for

  • Copy, run: the standard library answers every call in the file.

Putting it to use

Output lines are prefixed (slept ms:, negative is no-op:, interrupted, flag cleared:), making the effect of each step easy to see.

The core lines of the flow

return (System.nanoTime() - start) / 1_000_000;
Thread.sleep(Duration.ofSeconds(30));
Thread.sleep(Duration.ofMillis(50));

Interactive Tools for This Topic

FAQ

What does Thread Sleep Duration Interrupt Latency print when run?
No setup needed: run the file and look for labeled lines like `slept ms:`, `negative is no-op:`, `interrupted, flag cleared:` in the output.