How does the restored interrupt in a Runnable.run InterruptedException propagate to the caller method?

Viewed 45

Code as below:

import java.util.concurrent.TimeUnit;

public class Test {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        thread.interrupt();
        System.out.println(thread.isInterrupted());
    }
}

Sometimes System.out.println(thread.isInterrupted()); prints true while sometimes prints false !

So how can the code higher up the call stack see that an interrupt was issued as described in JCIP 5.4?

1 Answers

That's the way to go, but your code faces a race condition. Your main thread executes thread.isInterrupted() immediately after calling thread.interrupt().

The documentation states that

If this thread is blocked in an invocation of [...] or sleep(long, int) methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

Give thread thread a fair chance to catch the exception and to set the interrupt status, that is join the thread or wait a moment, at least.

Related