$show=/label

How to Kill a Java Thread

SHARE:

A quick guide and learn how to properly stop a Thread in Java using different methodologies such as atomic boolean, volatile boolean and interrupt().

1. Overview


In this tutorial, We will cover stopping a Thread in Java which is not that simple since the Thread.stop() method is deprecated. Because Thread.stop() method can lead to the monitored objects being corrupted. But, Still, many developers and applications are still using Thread.stop() method. Because they are not aware of its problems (monitored objects being corrupted.).

How to Kill a Java Thread Or How to stop a thread without using stop() method

let us see what are the other possible ways to stop the thread from its execution. This is a tricky topic for intermediate developers. Please read twice and practice the programs.

How to Kill a Java Thread


2. Stop Thread By Using Flag (+ volatile)


In this approach, We will be using a flag which type is boolean. This flag decides whether the thread should run or not. Once thread is started, the flag is set to true.

Let us take a look at the below class CustomThread which has the AtomicBoolean instance variable which works well among multiple threads. This class implements the Runnable interface and provide an implementation for the abstract method run(). Inside run() method, created a while loop which runs for all the time and while loop checks the condition flag value is true. And also provided a stop() method which sets flag value to false upon invocation and stop() method must be public.

class CustomThread implements Runnable {

 Thread current;
 long interval;
 AtomicBoolean flag = new AtomicBoolean();

 public CustomThread(int interval) {
  this.interval = interval;
  flag.set(true);
 }

 public void stop() {
  flag.set(false);

 }

 @Override
 public void run() {

  while (flag.get()) {
   System.out.println("Running a task");
   try {
    Thread.sleep(interval);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }

  System.out.println("Task is stopped by flag.");

 }
}

Now, Creating a thread and call start() method. Thread invokes Thread class start() method which in turn calls CustomThread run() method.

package com.java.w3schools.blog.java.program.to.threads;

import java.util.concurrent.atomic.AtomicBoolean;

public class ThreadStopFlagExample {

 public static void main(String[] args) throws InterruptedException {

  CustomThread runnable = new CustomThread(1000);
  Thread customThread = new Thread(runnable);
  customThread.start();
  
  Thread.sleep(5000);
  
  runnable.stop();

 }
}

Output:

Running a task
Running a task
Running a task
Running a task
Running a task
Task is stopped by flag.

We have started a thread and sleeping for 5 seconds. After then invoked stop() method which sets flag to true. run() method while loop checks the condition and flag value is now false. So, the execution pointer comes out of loop and stops the thread.

Note: Instead of AtomicBoolean type, we can use the primitive boolean to stop thread but which any modifications are done to primitive flag from the main thread, those changes are not visible to the child thread. All changes are done to the boolean variable are made to local memory. so we need to declare this as volatile which writes every update to the main memory. So that thread can see the updated value. volatile can used in many other scenarios.

3. Interrupting a Thread using interrupt()


There is another way to kill the thread using interrupt() method. But, this interrupt method will not stop() the thread immediately. First, let us create a program that calls interrupt() method.

See the below example program using interrupt().

package com.java.w3schools.blog.java.program.to.threads;

import java.util.concurrent.atomic.AtomicBoolean;

public class ThreadStopInterruptExample {

 public static void main(String[] args) throws InterruptedException {

  CustomInterruptThread runnable = new CustomInterruptThread(1000);
  Thread.sleep(5000);
  runnable.interrupt();

 }
}

class CustomInterruptThread implements Runnable {

 Thread current;
 long interval;
 AtomicBoolean flag = new AtomicBoolean();

 public CustomInterruptThread(int interval) {
  this.interval = interval;
  current = new Thread(this);
  flag.set(true);
  current.start();

 }

 public void interrupt() {
  current.interrupt();

 }

 @Override
 public void run() {

  while (flag.get()) {
   System.out.println("Running a task");

  }

  System.out.println("Task is stopped by flag.");
 }
}

This program runs in an infinite loop because the thread is not stopped by interrupt() method even though we called interrupt() intentionally. It prints continuously "Running a task".

You must take note in interrupt() is that thread will be interrupted from its execution if and only if the Thread is in sleep() state otherwise no effect to the thread by interrupt() method.

Do the following changes and thread will get interrupted by interrupt() method and comes into InterruptedException. After interrupt(), set the flag to false to come out of thread.

Modify the code in run() and interrupt() method as below.

public void interrupt() {
 System.out.println("Calling interrupt() method");
 current.interrupt();
 flag.set(false);
}

@Override
public void run() {

 while (flag.get()) {
  System.out.println("Running a task");

  try {
   Thread.sleep(interval);
  } catch (InterruptedException e) {
   System.out.println("thread is in sleep state and it is interrupted.");
  }
 }

 System.out.println("Task is stopped by flag.");
}

Output:

Running a task
Running a task
Running a task
Running a task
Running a task
Calling interrupt() method
thread is in sleep state and it is interrupted.
Task is stopped by flag.

Note: This is most useful if the thread is set to long-running intervals and other threads will not get the chance to execute. So, We need to follow this use case.

4. Conclusion

In this article, We have seen how to kill a Thread without using the deprecated method Thread.stop() method. Shown the clear ways using the atomic flag and interrupt() method to shut down the thread. I have seen using the flag concept in my project to stop the thread which is still stable and working pretty well. This is absolutely preferable instead of calling the deprecated stop() method and risking locking forever and memory corruption.

Reference

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: How to Kill a Java Thread
How to Kill a Java Thread
A quick guide and learn how to properly stop a Thread in Java using different methodologies such as atomic boolean, volatile boolean and interrupt().
https://1.bp.blogspot.com/-J5XdTdVlj_k/Xg-Jl3z7dDI/AAAAAAAACJA/7D6pajrKNHgf9GeIxPQ8juT9B6o-iH0sgCLcBGAsYHQ/s640/How%2Bto%2BKill%2Ba%2BJava%2BThread.png
https://1.bp.blogspot.com/-J5XdTdVlj_k/Xg-Jl3z7dDI/AAAAAAAACJA/7D6pajrKNHgf9GeIxPQ8juT9B6o-iH0sgCLcBGAsYHQ/s72-c/How%2Bto%2BKill%2Ba%2BJava%2BThread.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/01/java-thread-stop.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/01/java-thread-stop.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content