Library contents

Groovy 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

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

Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.

groovy Lesson.groovy

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.groovy
Thread.currentThread().interrupt()
try {
    Thread.sleep(1000)
} catch (InterruptedException problem) {
    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