Quiz: Thread Interruption in Java: interrupt() and How to Stop a Thread

Total: 8 questions

1. 

Why is Thread.stop() deprecated, and what happens when you call it today?

Thread.stop() killed a thread at an arbitrary point: 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 inconsistent and immediately became visible to other threads. Think of a money transfer where the amount has been taken from account A but not yet added to account B. finally does not help: the exception can arrive inside it too.

The method was deprecated back in Java 1.2, is marked @Deprecated(forRemoval = true), and since Java 20 always throws UnsupportedOperationException (javac issues a [removal] warning). suspend() and resume() froze a thread together with its monitors and led to deadlocks; since Java 20 they also throw UnsupportedOperationException, and in Java 23 they were removed from Thread.

Instead of stop(), you ask the thread to stop: interrupt() or your own flag, then join(). The thread ends where it checked the flag itself, which is a point where its data is consistent.

2. 

How do you stop a thread with a volatile flag, and when is such a flag not enough?

Declare a field volatile boolean running = true, check it in the loop condition while (running), and let a stop method called from another thread write false. Without volatile, the worker thread is allowed to never see the new value. An AtomicBoolean works just as well as a volatile boolean.

The flag is enough while the thread is busy computing. But if the thread is sleeping in sleep(), waiting in wait() or in BlockingQueue.take(), the flag will not wake it: the loop condition is checked only when the wait ends on its own. A consumer on an empty queue stays in WAITING after the flag is cleared.

The fixes: interrupt the thread with interrupt() (it leaves the wait with InterruptedException), or put a "poison pill" into the queue — a special element that tells the consumer to exit the loop.

3. 

What does Thread.interrupt() do, and how should a thread respond to it?

t.interrupt() sets the interrupt flag of thread t. If t is waiting in an interruptible method (sleep(), wait(), join(), take() and so on), it wakes up with an InterruptedException. If the thread is simply executing code, nothing happens except that the flag becomes true. Stopping is the thread's own job.

That is why a worker loop is written as while (!Thread.currentThread().isInterrupted()), with InterruptedException caught around the loop. The check in the condition catches an interrupt during computation, the exception catches it during a wait.

Three more properties: interrupt() does not wait for the thread to stop and returns at once — use join() to wait for it; a thread in WAITING/TIMED_WAITING goes back to RUNNABLE, while a thread in BLOCKED keeps waiting for the monitor; a call to interrupt() happens-before the interrupted thread detects the interrupt.

A thread can interrupt itself: Thread.currentThread().interrupt() simply sets its own flag. Interrupting a thread that has not started yet or has already finished is pointless: per the Javadoc it "need not have any effect", so you cannot count on the flag being kept.

4. 

Which blocking methods respond to interrupt(), and what happens to the interrupt flag?

Methods declared with throws InterruptedException throw the exception and clear the flag: sleep(), join(), wait() (after reacquiring the monitor), BlockingQueue.put()/take(), Future.get(), CountDownLatch.await(), Semaphore.acquire(), lockInterruptibly(), tryLock(time, unit), Condition.await(). The flag is cleared because the stop request has moved into the exception: otherwise code that decided to wait again would get a new exception right away.

The flag stays true with an InterruptibleChannel (FileChannel, SocketChannel) — the channel is closed and the thread gets ClosedByInterruptException — and with Selector.select() and LockSupport.park(), which simply return.

No response: entering synchronized (the thread stays BLOCKED), Lock.lock(), Condition.awaitUninterruptibly(), InputStream.read() (System.in, a socket in a platform thread) and plain computation. A thread blocked reading a socket is stopped with Socket.close() — it gets a SocketException. In a virtual thread (JEP 444), Socket operations are interruptible: interrupt() wakes the thread and closes the socket.

5. 

What is the difference between isInterrupted() and Thread.interrupted()?

t.isInterrupted() is an instance method: it returns the flag of thread t and leaves it alone. Use it in a worker loop condition and for any other check. Thread.interrupted() is a static method: it returns the flag of the current thread and resets it to false, so a second call in a row almost always returns false.

The clearing check is dangerous in helper methods: the method notices the interrupt through Thread.interrupted() and returns, but the flag is already cleared, and the outer while (!isInterrupted()) loop keeps going. The right options are to check with isInterrupted() or to turn the flag into an exception: if (Thread.interrupted()) throw new InterruptedException(); — that is how the JDK's interruptible methods work.

A common mistake is worker.interrupted(): because the method is static, the call compiles, but it reads and clears the flag of the calling thread, not of worker. To find out whether another thread is interrupted, use worker.isInterrupted().

6. 

How do you write a thread that stops cleanly on interrupt()?

The worker 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 until the thread has actually finished and run its finally:

Thread worker = new Thread(() -> {
    try {
        while (!Thread.currentThread().isInterrupted()) {
            doStep();
            Thread.sleep(400);
        }
    } catch (InterruptedException e) {
        // exit: the exception is caught at the top level of run()
    } finally {
        releaseResources();
    }
});
worker.start();
// ...
worker.interrupt();
worker.join();

There is no need to restore the flag in this catch: after finally the thread ends, and there is nobody left to tell. If the loop lived in a helper method called by someone else's code, you would have to restore the flag or rethrow the exception. The isInterrupted() check is worth having even if the loop already calls sleep(): without it, the reaction is delayed until the next wait.

Stopping on timeout: worker.join(2000); if (worker.isAlive()) { worker.interrupt(); worker.join(); }. The thread stops only if it responds to interruption.

7. 

Why combine a volatile stop flag with interrupt()?

Each approach has its own weakness. A flag does not wake a thread from sleep(), wait() or a queue. Interruption is fragile: a single library with an empty catch (InterruptedException e) {} is enough to clear the flag for good.

So in a task that has computation, waiting and third-party code, the stop method does both:

void shutdown() {
    running = false;          // nobody can clear this one
    Thread t = runner;        // volatile field, set at the start of run()
    if (t != null) {
        t.interrupt();        // wakes it from sleep(), take(), wait()
    }
}

and the loop checks while (running && !Thread.currentThread().isInterrupted()). Without running = false, a thread running code that swallows the interrupt never stops; without interrupt(), it stops, but only after it finishes sleeping. The runner field is needed because a Runnable does not know which thread runs it. Only interrupt threads you own: a task in a pool is stopped through the pool.

8. 

How do you cancel a task in a thread pool, and why might it not stop?

A single task is cancelled with Future.cancel(true), the whole pool is stopped with shutdownNow(). Both simply call interrupt() on the worker threads. A task that neither checks the flag nor waits in interruptible methods runs to the end anyway, and the pool waits for it: awaitTermination() returns false, and an endless "deaf" task keeps the program from ever exiting.

To stop a task on timeout, pair future.get(2, TimeUnit.SECONDS) with future.cancel(true) in the TimeoutException handler.

CompletableFuture.cancel(true) does not interrupt the thread at all: the mayInterruptIfRunning argument has no effect, the future is marked as cancelled, and the task keeps running. Stopping such a task has to rely on your own flag.

If a task restores the interrupt flag, the next task on the same worker thread does not inherit it: ThreadPoolExecutor clears the flag before starting the next task unless the pool is stopping. After shutdownNow(), on the contrary, the flag on worker threads stays set.

Page 1 of 1