Library contents

Java InterruptedException

A thread waiting in an interruptible operation can receive InterruptedException. A handler that cannot propagate it can restore the interrupt status and return.

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

Java syntax
Thread.sleep(milliseconds)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

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
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        Thread.currentThread().interrupt();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException stop) {
            Thread.currentThread().interrupt();
            System.out.println("Shift ended");
            return;
        }
    }
}
Output
Shift ended

The example sets the interrupt flag before sleep, so the wait ends immediately. The handler restores the flag before leaving the worker.

Advertisements

Check that a worker passes on shutdown

A print worker stops waiting as its shift ends. The queue supervisor reads the interrupt flag afterward to decide whether it should schedule another job on that thread.

ResultShutdown requested
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        var worker = Thread.currentThread();
        worker.interrupt();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException stop) {
            worker.interrupt();
        }
        if (worker.isInterrupted()) System.out.println("Shutdown requested");
    }
}
Output
Shutdown requested

isInterrupted observes the restored flag without clearing it.

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
Code and output in Java
Java source
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;

class Main {
    public static void main(String[] args) throws Exception {
        Thread.currentThread().interrupt();
        try { Thread.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        System.out.println(Thread.interrupted());
    }
}
Output
true

What to watch for

The interrupted wait clears the status. Restore it with Thread.currentThread().interrupt() when callers need to see the shutdown request.

Documentation for InterruptedException