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;

  @Override
  public void run() {
    while (true) {
       if (shutdown) {
         break;
       }

       // TODO: your actual task code goes here

       if (shutdown) {
         break;
       }
       try {
          // your thread sleep interval
          Thread.sleep(6000);
       } catch (InterruptedException exp) {
          // ignore this error
       }
     }
  }

  public void shutdown() {
     if (isAlive()) {
        this.shutdown = true;
        this.interrupt();
        try {
           // wait till this thread dies
           this.join();
        } 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.

http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html

Related Articles

5 responses to “Java: How to stop a thread?”

  1. Found an another article that explains the power of interrupt concept.
    http://www.ibm.com/developerworks/java/library/j-jtp05236.html

  2. mala

    good one

  3. […] Thread pools and work queues 3. Java while loop and Threads! 4. How to restart thread in java? 5. Java: How to stop a thread? […]

  4. The producer–consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue

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

Leave a comment

I’m Venkat

A passionate software engineer with over 20 years of experience in the tech industry. Welcome to my digital playground where I share my journey through the ever-evolving world of software development and cloud technologies!