Video in progress

How do you stop a thread the right way? How does interrupt() work?

Thread.stop() is dangerous and no longer works since Java 20. The right way is interrupt(): it sets a "stop" flag on the thread, and the thread has to check it itself and exit cleanly.

📖 Answer

interrupt() doesn't force anything, it only asks. There are two cases:

  1. If the thread is in a wait such as sleep, wait, join or BlockingQueue.take, it gets an InterruptedException right away.
  2. If the thread is busy computing, only the flag is set, and the thread has to check it itself with Thread.currentThread().isInterrupted().
Runnable task = () -> {
    while (!Thread.currentThread().isInterrupted()) {
        try {
            Job job = queue.take();
            job.run();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // restore the flag
            break;
        }
    }
    log.info("worker to'xtadi");
};

Important: when an InterruptedException is thrown, the flag is cleared. That is why it is a habit to call interrupt() again in the catch, so the code above this one also knows a stop was requested.

ExecutorService.shutdownNow() and Future.cancel(true) also send exactly this interrupt(). If your task doesn't respond to an interrupt, they can't stop it either.