Thread Interruption in Java: interrupt() and How to Stop a Thread
Thread interruption in Java is the way to ask a thread to stop. There is no safe way to stop a thread from the outside: calling thread.interrupt() only sets the thread’s interrupt flag, and the thread itself decides when to finish. It checks the flag with isInterrupted(), or gets an InterruptedException if it was waiting in a blocking method (sleep(), wait(), join(), BlockingQueue.take()) at the moment of interruption, and returns from run(). The old Thread.stop() method is deprecated for removal and, since Java 20, always throws UnsupportedOperationException.
// in the worker thread
while (!Thread.currentThread().isInterrupted()) {
doStep(); // the next piece of work
}
// in the controlling thread
worker.interrupt(); // ask it to stop
worker.join(); // wait until it has actually finished That’s why you can’t just replace worker.stop() with worker.interrupt() in old code and call it done. If the thread is crunching numbers and never checks the flag, it keeps running after interrupt() as if nothing happened — no exception, not a single line in the log. What interruption actually does and which methods it affects is covered in How interrupt() Works.
Why Thread.stop() Is Deprecated
Thread.stop() killed a thread at an arbitrary point in its code: it threw ThreadDeath inside the thread, and while the stack unwound, the thread released every monitor it held. Objects it was modifying under synchronized were left in an inconsistent state and immediately became visible to other threads. That’s why the method was deprecated as far back as Java 1.2, and in Java 20 it stopped working altogether.
Picture a money transfer under synchronized: the amount has already been taken from account A but not yet added to account B. stop() lands exactly between those two lines, the monitor is released, and other threads see money that has simply vanished. A finally block won’t save you here, because the exception can just as well arrive inside the finally itself. Interruption works the other way round: the thread stops where it checked the flag itself, which is a point where its data is consistent.
On a modern JDK, a call to stop() compiles with a warning and fails at runtime:
public class StopDeprecated {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// work
}
}, "worker");
worker.start();
try {
worker.stop(); // doesn't work on Java 20+
} catch (UnsupportedOperationException e) {
System.out.println("stop(): " + e.getClass().getSimpleName());
}
worker.interrupt(); // the right way
worker.join();
System.out.println("worker alive: " + worker.isAlive());
}
} StopDeprecated.java:11: warning: [removal] stop() in Thread has been deprecated and marked for removal
worker.stop(); // doesn't work on Java 20+
^
1 warning stop(): UnsupportedOperationException
worker alive: false suspend() and resume() behave the same way in Java 20–22, and Java 23 removed them from Thread altogether: “freezing” a thread together with its monitors led to deadlocks. Oracle explains why these methods were retired in Java Thread Primitive Deprecation.
Option 1: A volatile Stop Flag
The simplest way to stop a thread running a loop is a volatile boolean running field: the loop checks it in its condition, and another thread sets it to false. This works as long as the thread is busy computing. But if the thread is sleeping in sleep(), waiting in wait() or blocked on a queue, the flag won’t wake it up: the thread finds out about the stop request only when the wait ends on its own.
Without volatile, the worker thread is allowed to never see the new value at all — see The Visibility Problem in the volatile lesson. An AtomicBoolean works just as well as a volatile boolean. The more interesting limitation is a different one. Here a consumer takes messages from a queue, and our class’s own stop() method (not to be confused with Thread.stop()) clears the flag:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class FlagVsBlocking {
static class Consumer implements Runnable {
private final BlockingQueue<String> queue;
private volatile boolean running = true;
Consumer(BlockingQueue<String> queue) {
this.queue = queue;
}
public void stop() {
running = false;
}
@Override
public void run() {
try {
while (running) {
String message = queue.take(); // waits for the next message
System.out.println("processed: " + message);
}
System.out.println("exited via the flag");
} catch (InterruptedException e) {
System.out.println("exited via interrupt()");
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> queue = new LinkedBlockingQueue<>();
Consumer consumer = new Consumer(queue);
Thread thread = new Thread(consumer, "consumer");
thread.start();
queue.put("order 1");
Thread.sleep(200);
consumer.stop(); // the flag is cleared...
thread.join(1000);
System.out.println("1 s after stop(): " + thread.getState());
thread.interrupt(); // ...but only interrupt() can wake it
thread.join();
}
} processed: order 1
1 s after stop(): WAITING
exited via interrupt() After stop() the thread is still stuck in take() in the WAITING state: the while (running) condition is checked only before the next take(), and that won’t happen until a message shows up in the queue. “exited via the flag” is never printed. The fix is either interruption or a “poison pill” — a special queue element that tells the consumer to leave the loop. A “check the flag, then sleep” loop has a similar problem, described in Why sleep() in a Loop Is a Bad Way to Wait for an Event.
Option 2: How interrupt() Works
Calling t.interrupt() sets the interrupt flag of thread t. If t is waiting in an interruptible method at that moment — sleep(), wait(), join(), take() and others — it wakes up with an InterruptedException. If the thread is simply executing code, nothing happens except that the flag becomes true: checking it and exiting is the thread’s own job.
Hence the standard shape of a worker loop: while (!Thread.currentThread().isInterrupted()). The check in the condition catches an interrupt during computation, InterruptedException catches it during a wait. You need both: a thread that never waits won’t get the exception, and a thread that waits for hours won’t reach the loop condition.
Three more properties to keep in mind:
interrupt()doesn’t wait for the thread to stop; it returns immediately. To wait until the thread has really finished and run itsfinallyblocks, calljoin()afterwards (see Thread.join() and isAlive()).- An interrupted thread goes from
WAITINGorTIMED_WAITINGback toRUNNABLE, while a thread that isBLOCKEDon entry tosynchronizedkeeps waiting for the monitor. The difference between these states is explained in BLOCKED vs WAITING. - A call to
interrupt()happens-before the interrupted thread detects the interruption. Everything the interrupting thread wrote before the call is visible to the interrupted thread without extra synchronization (the rule is in the happens-before table).
Which Methods Respond to Interruption
Methods declared with throws InterruptedException respond to interrupt(): they throw the exception and clear the flag. NIO channels (InterruptibleChannel) are a special case: the channel is closed and the thread gets ClosedByInterruptException with the flag still set. Entering synchronized, Lock.lock() and classic I/O through InputStream.read() ignore interruption.
| Where the thread waits | What interrupt() does | Flag afterwards |
|---|---|---|
Thread.sleep(), Thread.join(), Object.wait() | Wakes the thread, throws InterruptedException; for wait() only after the monitor is reacquired (details) | Cleared |
BlockingQueue.put() / take(), timed offer() / poll() | Throws InterruptedException | Cleared |
Future.get() | Throws InterruptedException in the waiting thread; the task itself keeps running | Cleared |
CountDownLatch.await(), Semaphore.acquire() | Throws InterruptedException | Cleared |
Lock.lockInterruptibly(), tryLock(time, unit), Condition.await() | Throws InterruptedException (lockInterruptibly() example) | Cleared |
I/O on an InterruptibleChannel: FileChannel, SocketChannel | Closes the channel, throws ClosedByInterruptException | Stays true |
Selector.select() | Returns immediately, as after wakeup(), no exception | Stays true |
LockSupport.park() | Returns without an exception | Stays true |
Entering synchronized (BLOCKED) | Nothing: the thread keeps waiting for the monitor | true |
Lock.lock(), Condition.awaitUninterruptibly() | Nothing: the wait continues, the flag is restored after acquiring | true |
InputStream.read(): System.in, a socket stream in a platform thread | Nothing: the read continues | true |
| Plain computation | Nothing, until the code checks the flag itself | true |
The rows marked “Stays true” are exceptions to the rule “threw an exception — cleared the flag”. An NIO channel is closed entirely, not just the current operation: you can’t keep writing to it after the interrupt. You can see this without a second thread — just interrupt yourself before the write:
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class ChannelInterrupt {
public static void main(String[] args) throws Exception {
Path file = Files.createTempFile("interrupt", ".txt");
try (FileChannel channel = FileChannel.open(file, StandardOpenOption.WRITE)) {
Thread.currentThread().interrupt(); // flag set before the operation
try {
channel.write(ByteBuffer.wrap("data".getBytes()));
} catch (ClosedByInterruptException e) {
System.out.println("write(): " + e.getClass().getSimpleName());
}
System.out.println("channel open: " + channel.isOpen());
System.out.println("interrupt flag: " + Thread.interrupted()); // read and clear
} finally {
Files.delete(file);
}
}
} write(): ClosedByInterruptException
channel open: false
interrupt flag: true The practical consequence: if threads write to a FileChannel that is opened once for the whole application, interrupting any one of those threads closes the channel for everyone. In such code, handle the interrupt before writing — check the flag in the loop and leave without starting a new operation.
isInterrupted() vs Thread.interrupted()
isInterrupted() is an instance method: it returns the interrupt flag of the thread it’s called on and leaves the flag alone. Thread.interrupted() is a static method: it returns the flag of the current thread and resets it to false. Two Thread.interrupted() calls in a row will almost always return true and then false.
| Method | Whose flag | Changes the flag | When to use |
|---|---|---|---|
t.interrupt() | Thread t | Sets it to true | Ask a thread to stop; Thread.currentThread().interrupt() restores your own flag |
t.isInterrupted() | Thread t | No | Worker loop condition, checks anywhere in the code |
Thread.interrupted() (static) | Current thread | Resets it to false | Turn the flag into an exception: if (Thread.interrupted()) throw new InterruptedException(); |
public class InterruptedVsIsInterrupted {
public static void main(String[] args) {
Thread current = Thread.currentThread();
current.interrupt(); // interrupt ourselves
System.out.println("isInterrupted(): " + current.isInterrupted());
System.out.println("isInterrupted(): " + current.isInterrupted());
System.out.println("Thread.interrupted(): " + Thread.interrupted());
System.out.println("Thread.interrupted(): " + Thread.interrupted());
System.out.println("isInterrupted(): " + current.isInterrupted());
}
} isInterrupted(): true
isInterrupted(): true
Thread.interrupted(): true
Thread.interrupted(): false
isInterrupted(): false The clearing check becomes a problem when someone else still needs the flag. What does this program print? The outer loop checks the flag correctly, but a helper method uses Thread.interrupted():
public class SwallowedFlag {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
int chunks = 0;
while (!Thread.currentThread().isInterrupted() && chunks < 5) {
processChunk();
chunks++;
System.out.println("part " + chunks + " done");
}
}, "worker");
worker.start();
Thread.sleep(450);
worker.interrupt(); // lands in the second part
worker.join();
}
static void processChunk() { // ~300 ms of computation
long end = System.nanoTime() + 300_000_000L;
while (System.nanoTime() < end) {
if (Thread.interrupted()) { // checked and cleared
System.out.println(" processChunk: interrupt noticed, returning");
return;
}
}
}
} part 1 done
processChunk: interrupt noticed, returning
part 2 done
part 3 done
part 4 done
part 5 done The interrupt arrives at 450 ms, during the second part. processChunk() notices it and returns, but clears the flag along the way, so the outer loop happily carries on for three more parts. Without the chunks < 5 limit the thread would never stop. Replace the check with Thread.currentThread().isInterrupted() and the output ends at “part 2 done”. The other correct option is to declare throws InterruptedException on the method and write if (Thread.interrupted()) throw new InterruptedException();: the flag is cleared, but the interruption travels up the stack inside the exception. That’s how the JDK’s own interruptible methods are built.
worker.interrupted() doesn’t check worker
interrupted() is static, so worker.interrupted() called from main compiles, but it reads and clears the flag of main, not worker. To find out whether another thread is interrupted, use worker.isInterrupted(). It’s the same story as worker.sleep() — see Thread.sleep() Is a Static Method.
InterruptedException Handling: Why the Flag Is Cleared
When sleep(), wait() or take() throws InterruptedException, the interrupt flag has already been cleared: the stop request has moved from the flag into the exception. So a catch block has exactly two correct options — rethrow the exception or restore the flag with Thread.currentThread().interrupt(). An empty catch loses the stop request for good.
Why does the JDK clear the flag instead of leaving it set? Otherwise any code that caught the exception and decided to wait again would get a new exception right away and spin in a “wait — exception — wait” loop. Clearing hands the decision to whoever caught the exception: either they handle the interruption themselves (finish the task) or they have to pass it up. The handling options, with an example whose output shows the flag going false and back to true, are covered in InterruptedException: How to Handle It.
Example: A Thread That Stops Cleanly
A thread that stops cleanly checks the flag in its loop condition, catches InterruptedException around the whole loop and releases resources in finally. The controlling thread calls interrupt() and then join() to wait for the thread to actually finish.
public class GracefulWorker {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
int batch = 0;
try {
while (!Thread.currentThread().isInterrupted()) {
batch++;
System.out.println("processing batch " + batch);
Thread.sleep(400); // waiting: InterruptedException arrives here
}
System.out.println("flag seen in the loop condition");
} catch (InterruptedException e) {
System.out.println("interrupted during sleep(), flag = "
+ Thread.currentThread().isInterrupted());
} finally {
System.out.println("releasing resources, batches: " + batch);
}
}, "worker");
worker.start();
Thread.sleep(1000);
worker.interrupt(); // ask it to stop
worker.join(); // wait for finally to run
System.out.println("worker: " + worker.getState());
}
} processing batch 1
processing batch 2
processing batch 3
interrupted during sleep(), flag = false
releasing resources, batches: 3
worker: TERMINATED Batches start at 0, 400 and 800 ms, the third sleep() lasts until 1200 ms, and the interrupt arrives at 1000 ms — in the middle of the sleep. Hence the exception and false for the flag. “flag seen in the loop condition” is printed only if interrupt() hits the short window between the end of sleep() and the loop check; in this example that almost never happens, but the code is ready for it.
The flag isn’t restored in catch on purpose: the exception is caught at the top level of run(), after finally the thread ends, and there is nobody left to report the interruption to. If the loop lived in a helper method called by someone else’s code, the flag would have to be restored. Note the join() too: without it, main would print the state before the worker finished its finally, and could see RUNNABLE or TIMED_WAITING instead of TERMINATED.
Combining a Flag and interrupt()
When a task has both computation and waiting, and calls code you don’t control, the most reliable approach is a combination: the stop method clears your own volatile flag and calls interrupt() on the worker thread. Nobody can “swallow” the flag, and the interrupt wakes the thread from sleep(), wait() or a queue.
Why a flag if you already have interrupt()? Because interruption is fragile: a single library with an empty catch (InterruptedException e) {} is enough to clear the flag. In this example the “third-party” method legacyPoll() does exactly that:
public class FlagAndInterrupt {
static class Poller implements Runnable {
private volatile boolean running = true;
private volatile Thread runner;
void shutdown() {
running = false; // nobody can clear this one
Thread t = runner;
if (t != null) {
t.interrupt(); // wakes it from sleep(), take(), wait()
}
}
@Override
public void run() {
runner = Thread.currentThread();
int polls = 0;
while (running && !Thread.currentThread().isInterrupted()) {
polls++;
legacyPoll(polls);
}
System.out.println("Poller stopped after poll " + polls);
}
// third-party code that "swallows" the interrupt
private void legacyPoll(int n) {
System.out.println("poll " + n);
try {
Thread.sleep(300);
} catch (InterruptedException ignored) {
// flag cleared and not restored
}
}
}
public static void main(String[] args) throws InterruptedException {
Poller poller = new Poller();
Thread thread = new Thread(poller, "poller");
thread.start();
Thread.sleep(700);
poller.shutdown();
thread.join();
}
} poll 1
poll 2
poll 3
Poller stopped after poll 3 The third poll sleeps from 600 to 900 ms, and shutdown() is called at 700 ms. The interrupt cuts the sleep short, legacyPoll() silently swallows the exception, yet the loop still exits — thanks to the running flag. Remove running = false from shutdown() and the thread never stops: the interrupt flag is gone, and the loop condition knows no other signal. Remove t.interrupt() and the thread does stop, but 200 ms later, after it finishes sleeping. The longer the waits, the bigger that gap.
The runner field is needed because a Runnable on its own doesn’t know which thread runs it. Only interrupt threads you own: if the task runs in a pool, stop it through the pool rather than interrupting the pool’s worker thread directly.
Cancelling Tasks in a Thread Pool
To cancel a task in an ExecutorService, call Future.cancel(true); to stop the whole pool, call shutdownNow(). Both simply call interrupt() on the worker threads. A task that neither checks the flag nor waits in interruptible methods will run to the end anyway, and the pool will wait for it.
The Future methods table and a cancel(true) example are in Future: get(), Timeouts and Cancelling a Task, and the pool shutdown methods in Shutting Down a Pool. Here is what a “deaf” task looks like next to a “polite” one:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ShutdownNowIgnored {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(() -> { // doesn't check the flag
long end = System.nanoTime() + 1_500_000_000L;
while (System.nanoTime() < end) {
// 1.5 s of computation
}
System.out.println("deaf: ran to the end");
});
pool.submit(() -> { // checks the flag
while (!Thread.currentThread().isInterrupted()) {
Thread.onSpinWait();
}
System.out.println("polite: stopped on interrupt()");
});
Thread.sleep(200);
pool.shutdownNow(); // interrupt() on both threads
System.out.println("pool terminated after 0.5 s: "
+ pool.awaitTermination(500, TimeUnit.MILLISECONDS));
System.out.println("pool terminated after 2 s: "
+ pool.awaitTermination(2, TimeUnit.SECONDS));
}
} polite: stopped on interrupt()
pool terminated after 0.5 s: false
deaf: ran to the end
pool terminated after 2 s: true shutdownNow() interrupted both threads, but only the task that looks at the flag stopped. The other one finished its second and a half of computation, and only then did the pool terminate: the second awaitTermination() returned true about 1.5 s after the start, without waiting out its timeout. If the deaf task ran forever, the pool would never terminate and the program would never end.
CompletableFuture is different: its cancel(true) doesn’t interrupt the thread running the task at all — per the Javadoc, the mayInterruptIfRunning argument has no effect. The future is marked as cancelled, and the task keeps running (see Timeouts and Cancellation). Stopping such a task has to rely on your own flag.
Sometimes a background thread just shouldn’t keep the program from exiting, and there’s no need to stop it gracefully: then you make it a daemon. When that’s fine and when it loses data is covered in When to Use Daemon Threads and When Not To.
Virtual, Unstarted and Finished Threads
Virtual threads (Java 21) are interrupted exactly like platform threads: the same flag, the same isInterrupted() and InterruptedException. There is one difference, and it favours virtual threads: blocking operations on java.net.Socket, ServerSocket and DatagramSocket are interruptible in a virtual thread — per JEP 444, an interrupt wakes the thread and closes the socket. In a platform thread, a socket read doesn’t react to interrupt().
Interrupting a thread that hasn’t started yet or has already finished is pointless. The Java 21 Javadoc for Thread.interrupt() puts it carefully: “Interrupting a thread that is not alive need not have any effect.” There’s no exception, but you can’t count on the flag surviving until start() or being visible after the thread ends: the behaviour isn’t guaranteed. Interrupt a thread after start(), and for “cancel before it runs” use your own flag or Future.cancel() — a task cancelled while still in the pool’s queue never starts.
A thread can also interrupt itself: Thread.currentThread().interrupt() throws nothing and just sets its own flag. That’s the call used to restore the flag in catch, and in the ChannelInterrupt example above it replaced a second thread.
Frequently Asked Questions
How do I stop a thread blocked in System.in.read() or reading from a Socket?
interrupt() won’t help here: classic I/O through an InputStream in a platform thread ignores interruption. For a socket, close it from another thread: per the Javadoc of Socket.close(), a thread blocked reading from it gets a SocketException. For the console there’s no reliable way — such a thread is made a daemon or reads through an NIO channel. In a virtual thread, a socket read is interrupted by a plain interrupt() (see the section on virtual threads).
How do I stop a thread that didn’t finish within a time limit?
Wait for it with a timeout and interrupt it if it’s still alive: worker.join(2000); if (worker.isAlive()) { worker.interrupt(); worker.join(); }. For a task in a pool, the same is done by future.get(2, TimeUnit.SECONDS) plus future.cancel(true) in the TimeoutException handler. Either way, the thread stops only if it responds to interruption.
If a pool task restores the interrupt flag, does the next task get it?
No. ThreadPoolExecutor clears the worker thread’s flag before running the next task, unless the pool is shutting down. A restored flag tells code higher up the stack about the interruption within the current task and doesn’t leak into neighbouring tasks. After shutdownNow(), on the contrary, the pool makes sure the flag stays set on its worker threads.
Do I need isInterrupted() if the loop already calls sleep()?
You should still have it. sleep() throws even if the flag was set earlier, during computation, so the thread will stop sooner or later. But the reaction is delayed until the next sleep(), and with long work between waits that’s noticeable. The check in the loop condition costs nothing and stops the thread before the next step starts, as in the GracefulWorker example.
Practice
Reinforce this lesson with hands-on tasks, each with a level and a time estimate.
All module tasks →
Comments