YAJC become Java programmer
78 subscribers
8 photos
30 links
Yet another Java channel about programming
Download Telegram
How to Stop a Thread in Java: The Right Way

Stopping a thread in Java is a common topic in job interviews. While the question seems simple, it’s important to understand the right way to do it, especially if you want to avoid bugs 🐞 in your applications.

Why Not Use Thread.stop()?
Java used to provide a method called Thread.stop(), but it’s considered unsafe and has been deprecated since Java 2. It can leave objects in an inconsistent state and lead to unpredictable behavior.

The Right Approach: interrupted flag
In Java, stopping a thread is often done by using the interruption mechanism rather than forcefully terminating it. The isInterrupted() method is a clean, thread-safe way to signal a thread to stop without causing unpredictable behavior. Here’s how you can do it.

How It Works
When you want to stop a thread, you call Thread.interrupt() on the thread instance. This doesn’t stop the thread immediately, but it sets an internal interrupt flag. Inside the thread, you should check whether this flag is set by using the isInterrupted() method and stop the thread’s work if needed.


class MyRunnable implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Thread is running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // reset the interrupted flag
System.out.println("The thread is interrupted. Going to finish the thread.");
}
}
System.out.println("Thread has been interrupted and stopped.");
}
}

public class Main {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new MyRunnable());
thread.start();

// Let the thread run for a while
Thread.sleep(3000);

// Interrupt the thread
thread.interrupt();
}
}


You can try this example online: https://nextleap.app/online-compiler/java-programming/j4qe1j77a and expect an output similar to the following:

Thread is running...
Thread is running...
Thread is running...
The thread is interrupted. Going to finish the thread.
Thread has been interrupted and stopped.


Why Call Thread.currentThread().interrupt()?
When a thread is interrupted and it's performing a blocking operation like Thread.sleep(), wait(), or certain I/O tasks, an InterruptedException is thrown. This exception clears the thread’s interrupted status, meaning that after catching the exception, the interrupt flag is reset to false.

If your code doesn’t call Thread.currentThread().interrupt() after catching the exception, the thread will lose the information that it was interrupted, and you might miss the chance to stop the thread properly.

By calling Thread.currentThread().interrupt(), you restore the interrupted status and allow other parts of the thread (or the rest of the program) to know that the thread was interrupted, so they can handle it accordingly.

🛑 Another way to stop a Thread
Even with the advantages of using Thread.interrupt(), some developers still opt for custom flags, especially for non-blocking tasks ( like those that don’t involve Thread.sleep() ).

While it can work, I don't really see the need to replicate functionality that Java already provides. The KISS principle (Keep It Simple, Stupid) definitely applies here — why reinvent the wheel or redo what's already built into the language? Plus, software tends to evolve. Even if your thread isn’t using blocking operations right now, that could easily change down the line. When that happens, you’ll probably have to refactor anyway and switch to the interruption mechanism to handle thread interruptions properly.

I genuinely hope this material helps you when you face a job interview. Sooner or later, you'll encounter questions like this, and being prepared can make all the difference. Best of luck! 😌

#java #intermediate #interview