Kotlin InterruptedException
An interrupt ends this waiting operation and clears the JVM thread’s interrupt status.
A simple example
InterruptedException
- Start with A thread is waiting
- Do this Interrupt the wait
- Result Interrupted wait
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.jarStop 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.
fun main() {
Thread.currentThread().interrupt()
try {
Thread.sleep(1000)
} catch (problem: InterruptedException) {
Thread.currentThread().interrupt()
println("Shift ended")
}
}
Shift ended
The interrupt was already pending when the wait began. The handler restores the status and the example ends.
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.
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.
What to watch for
Restore the flag when handling the exception locally so the owner of the worker can observe it.