Skip to lesson

Stop a thread politely with interrupt

Java has no safe way to kill a thread from outside. Instead, one thread asks another to stop with interrupt(), and the other thread's code notices the request and finishes cleanly.

The interrupt flag and isInterrupted()

An interrupt is a polite request to a thread to stop what it is doing; the thread must check for it or handle InterruptedException and end cleanly.

t.interrupt() sets a flag on thread t that means "please stop what you are doing". It does not stop the thread by force. The thread's own code must check the flag with isInterrupted() and then finish in a clean way.

Example 1 · A loop that checks the interrupt flag

InterruptFlagDemo.javaJava
public class InterruptFlagDemo {    public static void main(String[] args) throws InterruptedException {        Thread checker = new Thread(() -> {            long checked = 0;            while (!Thread.currentThread().isInterrupted()) {                checked++;            // check one more PNR status            }            System.out.println("pnr-checker: stopped after checking " + checked + " PNRs");        }, "pnr-checker");
        checker.start();        Thread.sleep(50);             // let it work for a while        checker.interrupt();          // ask it to stop        checker.join();        System.out.println("main: checker alive = " + checker.isAlive());    }}
Sample output
pnr-checker: stopped after checking 48713206 PNRs
main: checker alive = false

What this code does

  • The loop condition reads the flag on every pass. interrupt() sets it, the condition turns false, and the thread leaves the loop and prints its total.
  • The count changes on every run, because it depends on how fast the computer is and when main got to interrupt(). Without the check, interrupt() would have no effect on this loop at all.
  • t.interrupt(): sets t's flag (and wakes t if it is blocked in sleep, join or wait).
  • t.isInterrupted(): reads the flag, leaves it unchanged.
  • Thread.interrupted() (static): reads the current thread's flag and clears it.

This is called cooperative cancellation: one thread asks, the other decides when it is safe to stop. A long loop should check the flag on every pass, for example while (!Thread.currentThread().isInterrupted()).

InterruptedException clears the flag

If the thread is blocked in sleep, join or wait when it is interrupted, that method wakes up at once and throws InterruptedException. At the same moment the flag is cleared, set back to false.

Example 2 · Waking a sleeping thread, and the cleared flag

ClearedFlagDemo.javaJava
public class ClearedFlagDemo {    public static void main(String[] args) throws InterruptedException {        Thread alarm = new Thread(() -> {            try {                Thread.sleep(5000);   // would sleep for 5 seconds                System.out.println("alarm: slept the full time");            } catch (InterruptedException e) {                System.out.println("alarm: woken early, flag now = "                        + Thread.currentThread().isInterrupted());            }        }, "alarm");
        alarm.start();        Thread.sleep(50);        alarm.interrupt();        alarm.join();
        Thread.currentThread().interrupt();        // interrupt main itself        System.out.println("main: flag before sleep = " + Thread.currentThread().isInterrupted());        try {            Thread.sleep(1000);                    // flag already set: throws at once        } catch (InterruptedException e) {            System.out.println("main: sleep threw at once, flag now = "                    + Thread.currentThread().isInterrupted());        }    }}
Output
alarm: woken early, flag now = false
main: flag before sleep = true
main: sleep threw at once, flag now = false

What this code does

  • alarm did not sleep 5 seconds: interrupt() woke it and sleep threw InterruptedException. Inside the catch the flag is already false.
  • main sets its own flag, so its sleep throws immediately without waiting. Again the flag is cleared: the exception now holds the stop request.

The exception now carries the stop request, and the flag no longer does. So whoever catches the exception decides whether the request lives on or is lost.

If the flag is already set when the thread calls sleep, sleep throws straight away.

Restoring the interrupt in a catch block

Restoring the interrupt means calling Thread.currentThread().interrupt() inside catch (InterruptedException e), so the flag is true again. Code further up, such as a loop that checks isInterrupted(), then still sees the stop request.

Example 3 · Swallowed versus restored interrupt

RestoreInterruptDemo.javaJava
public class RestoreInterruptDemo {    static int rounds(boolean restore) throws InterruptedException {        int[] done = {0};        Thread syncer = new Thread(() -> {            while (!Thread.currentThread().isInterrupted() && done[0] < 10) {                done[0]++;                         // sync one batch of attendance                try {                    Thread.sleep(30);                } catch (InterruptedException e) {                    if (restore) {                        Thread.currentThread().interrupt();   // keep the request                    }                    // with restore == false the request is swallowed here                }            }        }, "attendance-sync");
        syncer.start();        Thread.sleep(100);        syncer.interrupt();        syncer.join();        return done[0];    }
    public static void main(String[] args) throws InterruptedException {        System.out.println("Empty catch:       ran " + rounds(false) + " of 10 rounds");        System.out.println("Restored the flag: ran " + rounds(true) + " of 10 rounds");    }}
Sample output
Empty catch:       ran 10 of 10 rounds
Restored the flag: ran 4 of 10 rounds

What this code does

  • The interrupt almost always arrives during sleep, which clears the flag. With the empty catch the loop never sees the request and runs all 10 rounds; without the limit of 10 it would never stop.
  • Restoring the flag makes the loop condition false on the next check, so the thread stops after a few rounds. The exact number (often 4) depends on timing.

Example 4 · Let the exception travel to the top of run()

PropagateInterruptDemo.javaJava
public class PropagateInterruptDemo {    static void downloadChunk(int n) throws InterruptedException {        Thread.sleep(50);             // one chunk of the semester videos    }
    public static void main(String[] args) throws InterruptedException {        Thread downloader = new Thread(() -> {            try {                for (int n = 1; n <= 100; n++) {                    downloadChunk(n);                }                System.out.println("downloader: all chunks saved");            } catch (InterruptedException e) {                // caught once, at the top: clean up and end the task                System.out.println("downloader: cancelled, deleting the partial file");            }        }, "downloader");
        downloader.start();        Thread.sleep(120);        downloader.interrupt();       // the student pressed Cancel        downloader.join();        System.out.println("main: download stopped, alive = " + downloader.isAlive());    }}
Output
downloader: cancelled, deleting the partial file
main: download stopped, alive = false

What this code does

  • downloadChunk does not catch anything: throws InterruptedException passes the request up to the one place that knows what to do, the top of run().
  • No flag needs restoring here, because the task ends right after the catch. This is the cleanest pattern when you write all the code of the task yourself.

An empty catch swallows the interrupt: the request is lost and the thread keeps running. You have two good options instead: - Let it travel: declare throws InterruptedException on your helper methods and catch it once, at the top of run().

  • Or catch it, restore the flag, and stop the current work (return or break).

Find the bug

Find the interrupt bug

Click the line that is wrong in each snippet.

The worker must stop when it is interrupted.

Round 1 of 4

Why Thread.stop() is deprecated

Thread.stop() used to kill a thread at whatever line it was on. That could leave objects half-updated, for example money taken from one account but never added to the other, and other threads would then see broken data.

Example 5 · Thread.stop() on a modern JDK

StopDemo.javaJava
// Java 21public class StopDemo {    public static void main(String[] args) throws InterruptedException {        Thread worker = new Thread(() -> {            try {                Thread.sleep(5000);            } catch (InterruptedException e) {                System.out.println("worker: asked to stop, finishing cleanly");            }        }, "worker");        worker.start();
        try {            worker.stop();            // old, unsafe way        } catch (UnsupportedOperationException e) {            System.out.println("stop() threw " + e.getClass().getSimpleName());        }
        worker.interrupt();           // the polite way        worker.join();        System.out.println("main: worker alive = " + worker.isAlive());    }}
Output
stop() threw UnsupportedOperationException
worker: asked to stop, finishing cleanly
main: worker alive = false

What this code does

  • On Java 20 and later, stop() does nothing except throw UnsupportedOperationException (javac also warns that it is deprecated for removal). On older JDKs it really killed the thread, which is exactly what made it dangerous.
  • interrupt() lets the worker's own catch decide how to finish, so nothing is left half-done.

It was deprecated in Java 1.2, marked for removal in Java 18, and since Java 20 it always throws UnsupportedOperationException. The only correct way to stop a thread is to ask it with interrupt() (or your own stop signal) and let its code finish cleanly.

Next step

Check your understanding

12 quick questions