InterruptedException

Eric Kolotyluk eric at kolotyluk.net
Wed Dec 22 18:52:31 UTC 2021


I am embarrassed to bring this up here, but I cannot solve this little
puzzle

public Duration sleep(Consumer<InterruptedException> exceptionHandler) {
    final var duration = getDuration();
    try {
        Thread.sleep(duration);
    } catch (InterruptedException interruptedException) {
        if (exceptionHandler == null)
            System.out.println("Lag: ignoring interrupt, interrupted =
" + Thread.currentThread().isInterrupted());
        else
            exceptionHandler.accept(interruptedException);
    }
    finally {
        return duration;
    }
}

When I do a thread.interrupt() I see the following output

Lag: ignoring interrupt, interrupted = false

where I expected interrupted = true and eventually the thread does stop
prematurely, where my intention was that the interrupt just be ignored...Is
the call to println() stopping the thread prematurely? I discovered this
interesting scenario while writing unit tests for my Lag API.

For decades my understanding of catching an InterruptedException was that
it *did not* reset the isInterrupted() flag.

There is nothing in Class InterruptedException
<https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/InterruptedException.html>
that indicates that just catching the exception changes the status of this
flag. Could someone please clarify this in the JavaDoc.

Or maybe my misunderstanding goes deeper, but my intuition has really
failed me here... I was going to test this with Virtual Threads, but I
wanted to understand Platform Threads better first...

Sometimes reasoning about concurrency hurts my brain...

Cheers, Eric


More information about the loom-dev mailing list