How to Kill Java Thread

How to Kill Java Thread

In this article, we will discuss the clean way to Kill Java Thread, this is necessary to understand as Java had already deprecated Thread.stop() methods.

 

Introduction

Oracle deprecated Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit because of some underlying thread safety issues.  There are few recognized and well-accepted ways to accomplish this and in this article, we will cover 2 approached to Kill a Thread in Java.

  • Using a Flag
  • Interrupting a Thread.

 

1. Use a Flag

One of the easy approaches is to use thread to show if a Thread is running or not and use this flag to take corrective action based on your requirement, here is a sample code outlining how to Kill Java Thread using a flag.

public class KillThreadUsingFlag implements Runnable {


    private final AtomicBoolean running = new AtomicBoolean(false);
    private Thread thread;

    /**
     * When an object implementing interface <code>Runnable</code> is used to create a thread,
     * starting the thread causes the object's <code>run</code> method to be called in that
     * separately executing thread. <p> The general contract of the method <code>run</code> is that
     * it may take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {

        while (running.get()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
        }
        System.out.println("Shutting down thread");
    }

    public void shutdown() {
        running.set(false);
    }

    public void start() {
        thread = new Thread(this);
        thread.start();
    }

    public static void main(String[] args)
            throws InterruptedException {
        KillThreadUsingFlag process = new KillThreadUsingFlag();
        process.start();
        Thread.sleep(5000);
        process.shutdown();
    }
}

In the above example. we can control execution by setting our running variable to false.In our example, we have used AtomicBoolean for concurrency, in case you do not want to use it (which is not recommended), you need to make sure that Boolean flag used by you in your code should be volatile.

 

2. Interrupting a Thread

Above code looks good but have main points which need to be taken into account before we take above approach

  • It will become more complicated in case we have lots of threads and we need to ensure that those are finished by using join() method.
  • Do we really need to define a Boolean flag as Java already provide this feature using interrupted flag?
public class InterruptedExceptionExample implements  Runnable {


    private final AtomicBoolean running = new AtomicBoolean(true);


    /**
     * When an object implementing interface <code>Runnable</code> is used to create a thread,
     * starting the thread causes the object's <code>run</code> method to be called in that
     * separately executing thread. <p> The general contract of the method <code>run</code> is that
     * it may take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        try{

            while (running.get()){
                for(int i =0; i<3 ; i++){
                    System.out.println(i);
                }

                Thread.sleep(2000);
            }
        }
        catch (InterruptedException e){
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<?> future = executor.submit(new InterruptedExceptionExample());
        Thread.sleep(3000);
        executor.shutdownNow();
    }
}

 

There are a couple of important things in this code block

  • We are not swallowing the exception but passing it on to the system to ensure corrective action is being taken by system based on this exception

In the above example, we caught InterruptedException and immediately used Thread.currentThread().interrupt()  to interrupt our thread immediately.This is required since the interrupted flag is cleared once the exception is thrown and it can cause issue in case our code is running in the nested loop.

Just to summarize, Thread.interrupt() is the preferred/recommended way to cleanly Kill Java Thread if you still want to use flag approach you may have to wait for all the blocking operations to finish before you can use your flag based logic.

 

Summary

Java Concurrency is always a complex part of the JDK and working with threads can add more complexity if we are not aware of the inner working mechanism of the JDK. In this post, we covered different ways to Kill Java Thread. We discussed a flag based approach to handle this and finally, we covered the mechanism of interrupting a thread which is known as better and cleaner way to shut down threads in Java.

Comments are closed.