I want to stop a Java thread immediately but when I try the thread always takes some time before stopping. Is there a good way to force a Java thread to stop instantly?
-
@MohamedSaligh calling interrupt doesn't cause a Thread to stop. It simply sets the interrupted flag. It is still the responsibility of the code running in that thread to check that flag. – bhspencer Aug 16 '19 at 13:12
7 Answers
There is no good way to stop a thread instantly.
There is
Thread.stop()
, but it is dangerous and deprecated. Don't use it, unless:you fully understand the problems that make it dangerous,
you have thoroughly analyzed your code and determined that the problems do not apply and / or the risks are acceptable, and
you don't care that your application may end up stuck at a some version of Java if / when the method is removed1.
There was
Thread.stop(Throwable)
but it was equally dangerous2, deprecated and was removed3 in Java 11.There is
Thread.interrupt()
, but there is no guarantee that the thread will stop quickly, or even stop at all. The behavior will depend on whether the application thread code has been designed to notice and correctly respond to interrupts. (See below.)There is the approach of writing the thread to periodically check a flag; see this answer. (See below.)
The "check a flag" and interrupt()
approaches are largely the same. In both cases, the thread that expects to be interrupted needs to regularly check; e.g. by calling interrupted()
or isInterrupted()
or by checking a flag.
The difference between the approaches is that that the interrupt()
mechanism will work when the code is waiting for a notify()
, join()
, etcetera, or blocked in an I/O operation. Because of this, and because interrupt
is an accepted application independent way of doing this, it is usually preferable to implementing an application specific flag
mechanism.
1 - In the Java 18 prerelease javadocs, Thread.stop()
is now shown as "flagged for removal".
2 - Possibly more so. If you did a Thread.stop(new IOException())
for example, some code further up the call stack could easily catch the exception and subvert your "stop".
3 - You can still use the old "stop with an exception" functionality by calling the private Thread.stop0(Throwable)
method reflectively; see https://stackoverflow.com/a/67077495/139985. It would be better to avoid having to do that.

- 698,415
- 94
- 811
- 1,216
-
Upvoted just now, but last paragraph says interruption works if interrupted thread is blocked on I/O? Is that right? – Nathan Hughes Apr 13 '21 at 15:19
-
@NathanHughes - I am pretty sure so. The IO operation should throw `InterruptedIOException`. (It would be really bad if you couldn't interrupt a thread that is blocked in I/O ...) – Stephen C Apr 13 '21 at 15:30
-
I was under the impression some kinds of blocking I/O were handled and some weren’t, ill have to research, thanks. – Nathan Hughes Apr 13 '21 at 15:50
-
Some I/O is not interruptible at the kernel level ... but that is an OS limitation. If an I/O operation cannot be interrupted, then (on Linux I think) the process making the I/O request is unkillable. – Stephen C Apr 13 '21 at 15:55
There is one good way to safely (and quickly) force stop a thread:
System.exit(0)
Unfortunately, this has the side effect of killing all other threads.

- 25,859
- 43
- 145
- 213
-
29I'm not sure about downvoting the answer (for being a troll) or upvote it (because is technically correct) – Christian Vielma Jun 06 '16 at 15:34
-
3Even this method is not entirely safe depending on your application. If you have other threads that are supposed to store the data they have in memory on (before) shutdown, a System.exit(0) call would not trigger this store behaviour. @StephenC You made my laugh, +1. – Pieter12345 Jul 01 '16 at 22:58
-
3this is the most "hilarious" answer I found on stackoverflow in my life. I was going to downvote it but then I totally agree with @christian vielma – pdenti Mar 29 '18 at 14:11
-
3I don't think stackoverflow answers is a place for jokes, this is not a comedy website, keep these to the comment section. by giving a not serious answer you are actually wasting the time of the visitors who came here with the expectation of receiving a serious answer thus degrading the genuine mission of this whole website. – vasilevich Apr 10 '18 at 21:58
-
-
3
-
Not related answer. Moreover, a decent security manager does not allow exit() – Marco Torchiano Apr 13 '21 at 20:25
-
You could also pull the plug out of the computer to stop the thread instantly. – Daniel Williams Apr 17 '21 at 02:08
-
I agree that this is funny (don't have a firm opinion on appropriateness...). But I dispute @Christian Vielma's assertions that this is technically correct - it's only technically correct if you have an extremely loose definition of "safely" (certainly seems less safe than a call to Thread.stop(), which is also recognised as unsafe...) – Fr Jeremy Krieg May 10 '21 at 04:33
Running Thread cannot be stopped using Thread.Interrupt
, only waiting or blocking threads can be stopped using Thread.Interrupt
.But using a shared variable to signal that it should stop what it is doing. The thread should check the variable periodically,(ex : use a while loop ) and exit in an orderly manner.
private boolean isExit= false;
public void beforeExit() {
isExit= true;
}
public void run() {
while (!isExit) {
}
}

- 12,427
- 23
- 80
- 112
-
This isn’t accurate. A thread can check the state of the interrupt flag, the thread doesn’t have to be waiting or sleeping for interruption to work if the task is implemented correctly. – Nathan Hughes Apr 13 '21 at 15:33
-
In a multithreaded scenario, a mutation of the `isExit` boolean should be protected by some kind of syncrhonisation to insure the visibility of the mutation. One could mark it as volatile for example. – GPI Apr 13 '21 at 15:58
Do not under any circumstances use Thread.stop - if you are asking this question then you do not understand the Java threading model enough to safely use it.
The details, for the curious, are here: Java Thread Primitive Deprecation
If you get really good at Java concurrency, then you will understand why you should never use it, and that even if it's entirely safe within your own code, it makes your code contaminated and unusable by anyone else. Instead you will probably end up use the boolean variable trick or some other pattern to tell a thread when it should finish up and then exit.
Do not use Thread.stop. Ever.
You can still stop a thread with a specific exception even in later versions of the JDK.
You need to use reflection since the stop(Throwable)
has been removed but the underlying native method stop0(Throwable)
(which is also called by stop()
) is still there, though not visible.
Here is a simple method that can be used to actively stop a thread by throwing a given exception.
public static boolean stopWith(Thread t, Throwable e){
try {
Method m = Thread.class.getDeclaredMethod("stop0", Object.class);
m.setAccessible(true);
m.invoke(t, e);
m.setAccessible(false);
return true;
} catch (Exception e1) {
e1.printStackTrace();
}
return false;
}
This works as of JDK 11 but is is represents and illegal reflective access.
If your code uses modules, by default your module is not allowed to access non public members through reflection (because java.base/java.lang
is not open to other modules). Therefore an java.lang.reflect.InaccessibleObjectException
is thrown.
It is possible to override the default opening of the java.base/
module using the --add-opens
flag of the JVM,
e.g. --add-opens java.base/java.lang=
your.module
.
If your code is not using modules (i.e. Java 8 or previous), since for backward compatibility java.base/
is open to all unnamed modules (ALL-UNNAMED
) no exception is thrown.
But a non avoidable warning message is logged:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by YourCalss (file:/path/to/your/class/) to method java.lang.Thread.stop0(java.lang.Object)
WARNING: Please consider reporting this to the maintainers of TestSop
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

- 712
- 7
- 21
-
Note that 1) `Thread.stop()` is not "invisible" in Java 11. `Thread.stop()` is still `public`, and still deprecated. Check the Java 11 javadocs. 2) It was `Thread.stop(Throwable)` that was **removed** in Java 11 (not just made "invisible"). 3) What you are calling there is a private native method ... `stop0(Throwable)`. It happens to be the method that `Thread.stop()` calls. – Stephen C Apr 13 '21 at 15:38
-
The point is that if you really want to call `Thread.stop()` in Java 11, you don't have to resort to using nasty non-portable abstraction-breaking reflection to do it. You only need to use `stop0(Throwable)` if it is essential to use a specific exception other than `ThreadDeath`. (And if you do, you need to consider the something might catch your exception ... blocking the "stop". AFAIK that's why they *removed* `stop(Throwable)`.) – Stephen C Apr 13 '21 at 15:43
-
Yes, without `stop(Throwable)` you avoid blocking the `stop()` by mistake. But you can still block in on purpose by catching `ThreadDeath` or `Throwable`. BtW: Fixed the wrong details in the post. – Marco Torchiano Apr 13 '21 at 18:23
Your thread could be put in a while loop and check a boolean variable each time through. When you set the variable to false the loop would end and so would the thread. To end the thread before going through the current loop you can use the break keyword.
This avoids using deprecated methods such as Thread.stop()
.
private volatile boolean run = true; // Needs be volatile ... or changes may
// not be visible to all threads.
//Call this method to end your thread
void stopRunning(){
run = false;
}
//This loop would go into the overided run() method
while(run){
//Put your task here
}
The thread will finish the current task and then stop itself naturally.
If you need the thread to stop before finishing the task, you can check the run variable using an if/else anywhere in the loop and end the thread just like anywhere else.
while(run){
//Your code here
/*Be sure your not stopping the task at a point that will harm your program.*/
if(!run){break;}
}

- 698,415
- 94
- 811
- 1,216

- 359
- 3
- 15
In any and every language, you must never write code that depends on the execution pattern nor the timing of any other process or thread. You may send a signal asking for a thread to stop itself, or you may forcibly terminate it, but you still cannot predict exactly when the dirty deed will be done. You must carefully write code that is immune to so-called "race conditions."

- 8,490
- 5
- 28
- 41