Library contents

Kotlin InterruptedException

An interrupt ends this waiting operation and clears the JVM thread’s interrupt status.

A simple example

InterruptedException

  1. Start with A thread is waiting
  2. Do this Interrupt the wait
  3. Result Interrupted wait
The waiting operation can report interruption so the caller can stop or propagate that signal.

Syntax

Kotlin syntax
Thread.sleep(1000)
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Stop waiting when a shift ends

A dispatch worker is about to wait for another pickup. A shutdown request interrupts the worker, so it should stop waiting and preserve the signal for the code responsible for ending the shift.

ResultShift ended
Lesson.kt
fun main() {
    Thread.currentThread().interrupt()
    try {
        Thread.sleep(1000)
    } catch (problem: InterruptedException) {
        Thread.currentThread().interrupt()
        println("Shift ended")
    }
}
Output
Shift ended

The interrupt was already pending when the wait began. The handler restores the status and the example ends.

Advertisements

Handle the end of a scanning shift

The supervisor signals the scanning worker just before it waits. Observe the interrupt signal in a worker, restore it after handling an interrupted wait, and report whether a shutdown was requested.

GivenInterrupt requested
Worked resulttrue

Finish a quiet polling interval

The service completes its short wait with no shutdown request. Observe the interrupt signal in a worker, restore it after handling an interrupted wait, and report whether a shutdown was requested.

GivenNo interrupt
Worked resultfalse

What to watch for

Restore the flag when handling the exception locally so the owner of the worker can observe it.

Documentation for InterruptedException