Java: How to stop a thread?

Sun deprecated Thread.stop() because it is unsafe. They didn’t provide any direct alternative for this operation; instead they are making us to reinvent the wheel. Here I am sharing my style of safe thread stop implementation.

public class CustomThread extends Thread {

  private boolean shutdown;

  public void run() {
    while (true) {
       if (shutdown) {

       // TODO: your actual task code goes here

       if (shutdown) {
       try {
          // your thread sleep interval
       } catch (InterruptedException exp) {
          // ignore this error

  public void shutdown() {
     if (isAlive()) {
        this.shutdown = true;
        try {
           // wait till this thread dies
        } catch (InterruptedException e) {
           // safe to ignore this error

Hope the above code is self explanatory. I am happy with the above code because it uses most of the thread functions like join(), interrupt() and isAlive(). For web applications, threads can be started from context listener; you can invoke shutdown() method from Content Listener’s destroy() method. You can find more information in the below link.

Related Articles

5 Responses to Java: How to stop a thread?

  1. Venkat says:

    Found an another article that explains the power of interrupt concept.

  2. mala says:

    good one

  3. Pingback: Not losing your object when thread died « When IE meets SE…

  4. Pingback: Clete's Blog » Stopping a Thread in Java – Safely and Easily

  5. epl202020 says:


    Learn when and How to Stop the Thread,using jconsole or JvisualVM to indetify is the thread is running

Leave a Reply


You are commenting using your account. Log Out /  Change )

Google photo


Twitter picture


Facebook photo


Connecting to %s

%d bloggers like this: