Thread killing in java

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.

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 Runnable is used to create a thread, * starting the thread causes the object's run method to be called in that * separately executing thread. 

The general contract of the method run 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 Runnable is used to create a thread, * starting the thread causes the object's run method to be called in that * separately executing thread. 

The general contract of the method run is that * it may take any action whatsoever. * * @see Thread#run() */ @Override public void run() < try< while (running.get())< for(int i =0; iThread.sleep(2000); > > catch (InterruptedException e) < Thread.currentThread().interrupt(); >> public static void main(String[] args) throws InterruptedException < ExecutorService executor = Executors.newSingleThreadExecutor(); Futurefuture = 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.

Источник

How to Kill a Java Thread

announcement - icon

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

1. Introduction

In this brief article, we’ll cover stopping a Thread in Java – which is not that simple since the Thread.stop() method is deprecated.

As explained in this update from Oracle, stop() can lead to monitored objects being corrupted.

2. Using a Flag

Let’s start with a class that creates and starts a thread. This task won’t end on its own, so we need some way of stopping that thread.

We’ll use an atomic flag for that:

public class ControlSubThread implements Runnable < private Thread worker; private final AtomicBoolean running = new AtomicBoolean(false); private int interval; public ControlSubThread(int sleepInterval) < interval = sleepInterval; >public void start() < worker = new Thread(this); worker.start(); >public void stop() < running.set(false); >public void run() < running.set(true); while (running.get()) < try < Thread.sleep(interval); >catch (InterruptedException e) < Thread.currentThread().interrupt(); System.out.println( "Thread was interrupted, Failed to complete operation"); >// do something here > > >

Rather than having a while loop evaluating a constant true, we’re using an AtomicBoolean and now we can start/stop execution by setting it to true/false.

As explained in our introduction to Atomic Variables, using an AtomicBoolean prevents conflicts in setting and checking the variable from different threads.

3. Interrupting a Thread

What happens when sleep() is set to a long interval, or if we’re waiting for a lock that might never be released?

We face the risk of blocking for a long period or never terminating cleanly.

We can create the interrupt() for these situations, let’s add a few methods and a new flag to the class:

public class ControlSubThread implements Runnable < private Thread worker; private AtomicBoolean running = new AtomicBoolean(false); private int interval; // . public void interrupt() < running.set(false); worker.interrupt(); >boolean isRunning() < return running.get(); >boolean isStopped() < return stopped.get(); >public void run() < running.set(true); stopped.set(false); while (running.get()) < try < Thread.sleep(interval); >catch (InterruptedException e) < Thread.currentThread().interrupt(); System.out.println( "Thread was interrupted, Failed to complete operation"); >// do something > stopped.set(true); > > 

We’ve added an interrupt() method that sets our running flag to false and calls the worker thread’s interrupt() method.

If the thread is sleeping when this is called, sleep() will exit with an InterruptedException, as would any other blocking call.

This returns the thread to the loop, and it will exit since running is false.

4. Conclusion

In this quick tutorial, we looked at how to use an atomic variable, optionally combined with a call to interrupt(), to cleanly shut down a thread. This is definitely preferable to calling the deprecated stop() method and risking locking forever and memory corruption.

As always, the full source code is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Different Ways to Kill a Thread in Java

There is no official method to kill a thread in Java. Stopping a thread is entirely managed by the JVM. Although Java provides several ways to manage the thread lifecycle such as a start(), sleep(), stop() (deprecated in Java 1.1), etc. but does not provide any method to kill a thread and free the resources cleanly.

Oracle specified the reason for deprecating the stop() method as It is inherently unsafe. Stopping a thread causes it to unlock all its locked monitors.

1. Two Ways to Kill a Thread

Effectively, we can only signal the thread to stop itself and let the thread clean up the resources and terminate itself. In Java, we can send a signal to a thread in two ways:

  • By periodically checking a boolean flag
  • By interrupting the thread using Thread.interrupt() method

Let us learn about both methods:

In this method, we check a boolean flag periodically, or after every step in the task. Initially, the flag is set to false. To stop the thread, set the flag to true. Inside the thread, when the code checks the flag’s value to true, it destroys itself gracefully and returns.

Note that in this design, generally, there are two threads. One thread sets the flag value to true, and another thread checks the flag value. To ensure that both threads see the same value all the time, we must make the flag variable volatile. Or we can use AtomicBoolean class that supports atomic operations on an underlying volatile boolean variable.

public class CustomTask implements Runnable < private volatile boolean flag = false; private Thread worker; public void start() < worker = new Thread(this); worker.start(); >public void stop() < flag = true; >@Override public void run() < while (!flag) < try < Thread.sleep(500); System.out.println(Thread.currentThread().getName() + " Running. "); >catch (InterruptedException e) < Thread.currentThread().interrupt(); System.out.println("Thread was interrupted," + e.getMessage()); >> System.out.println(Thread.currentThread().getName() + " Stopped"); return; > >

Let us test this design by creating two threads and stopping them.

CustomTask task1 = new CustomTask(); CustomTask task2 = new CustomTask(); task1.start(); task2.start(); try < Thread.sleep(1000); task1.stop(); task2.stop(); >catch (InterruptedException e)
Thread-0 Running. Thread-1 Running. Thread-1 Running. Thread-0 Running. Thread-1 Stopped Thread-0 Stopped

3. By Interrupting the Thread

This method is also very similar to the previous approach of using a flag. The only difference is that we will interrupt the thread instead of setting the flag to false.

So inside the thread, we will keep checking the thread’s interrupt status, and when the thread is interrupted, we will stop the thread gracefully. To check the status of the interrupted thread, we can use the Thread.isInterrupted() method. It returns either true or false based on the thread’s interrupt status.

public class CustomTaskV2 implements Runnable < private Thread worker; public void start() < worker = new Thread(this); worker.start(); >public void interrupt() < worker.interrupt(); >@Override public void run() < while (!Thread.currentThread().isInterrupted()) < try < Thread.sleep(500); System.out.println(Thread.currentThread().getName() + " Running. "); >catch (InterruptedException e) < Thread.currentThread().interrupt(); System.out.println("Thread was interrupted with reason : " + e.getMessage()); >> System.out.println(Thread.currentThread().getName() + " Stopped"); return; > >

Interestingly, the code to test this design is similar to the previous one. Only the method call to thread.interrupt() is additional.

CustomTaskV2 task1 = new CustomTaskV2(); CustomTaskV2 task2 = new CustomTaskV2(); task1.start(); task2.start(); try < Thread.sleep(1100);isInterrupted task1.interrupt(); task2.interrupt(); >catch (InterruptedException e)
Thread-0 Running. Thread-1 Running. Thread-1 Running. Thread-0 Running. Thread was interrupted with reason : sleep interrupted Thread was interrupted with reason : sleep interrupted Thread-0 Stopped Thread-1 Stopped

This tutorial taught us to kill a running thread in Java using custom solutions. Even though the boolean flag solution is very good, it may not give the desired result for long-running tasks where the thread is waiting most of the time.

Sending an interrupt is a much better approach to stop a long-waiting thread.

Источник

Читайте также:  Тег SPAN
Оцените статью