I wrote a thread, it is taking too much time to execute and it seems it is not completely done. I want to stop the thread gracefully. Any help ?
6 Answers
The good way to do it is to have the run()
of the Thread guarded by a boolean
variable and set it to true
from the outside when you want to stop it, something like:
class MyThread extends Thread
{
volatile boolean finished = false;
public void stopMe()
{
finished = true;
}
public void run()
{
while (!finished)
{
//do dirty work
}
}
}
Once upon a time a stop()
method existed but as the documentation states
This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior.
That's why you should have a guard..
-
2See Jon Skeet's comment to Bart's answer - it applies to yours as well. – Péter Török Jul 07 '10 at 12:24
-
If "finished" change while you are doing your "dirty work" thread won't end, then you have to do a periodic check, for example with a sleep(x) in the loop, something that is not recomended and gives you a bad performance, so is really this a good aproach? – Hernán Eche Jul 30 '10 at 19:57
-
we are talking about quitting a thread gracefully. Forcing a thread to quit in the middle of its dirty work is not a graceful way to do it. You should always wait for next iteration unless you have got a specific reason to interrupt it.. – Jack Jul 30 '10 at 22:39
-
you can use wait and notify to avoid expressly loop checking – Hernán Eche Aug 02 '10 at 13:57
-
3This already doubles the built-in interrupt() and isInterrupted() methods. – Vladimir Ivanov Feb 13 '12 at 06:54
The bad part about using a flag to stop your thread is that if the thread is waiting or sleeping then you have to wait for it to finish waiting/sleeping. If you call the interrupt method on the thread then that will cause the wait or sleep call to be exited with an InterruptedException.
(A second bad part about the flag approach is that most nontrivial code is going to be utilizing libraries like java.util.concurrent, where the classes are specifically designed to use interruption to cancel. Trying to use the hand rolled flag in a task passed into an Executor is going to be awkward.)
Calling interrupt() also sets an interrupted property that you can use as a flag to check whether to quit (in the event that the thread is not waiting or sleeping).
You can write the thread's run method so that the InterruptedException is caught outside whatever looping logic the thread is doing, or you can catch the exception within the loop and close to the call throwing the exception, setting the interrupt flag inside the catch block for the InterruptedException so that the thread doesn't lose track of the fact that it was interrupted. The interrupted thread can still keep control and finish processing on its own terms.
Say I want to write a worker thread that does work in increments, where there's a sleep in the middle for some reason, and I don't want quitting the sleep to make processing quit without doing the remaining work for that increment, I only want it to quit if it is in-between increments:
class MyThread extends Thread
{
public void run()
{
while (!Thread.currentThread().isInterrupted())
{
doFirstPartOfIncrement();
try {
Thread.sleep(10000L);
} catch (InterruptedException e) {
// restore interrupt flag
Thread.currentThread().interrupt();
}
doSecondPartOfIncrement();
}
}
}
Here is an answer to a similar question, including example code.

- 94,330
- 19
- 181
- 276
You should not kill Thread from other one. It's considered as fairly bad habit. However, there are many ways. You can use return
statement from thread's run
method.
Or you can check if thread has already been interrupted and then it will cancel it's work. F.e. :
while (!isInterrupted()) {
// doStuff
}

- 18,367
- 27
- 104
- 155
-
-
3you can use empty return statement with void return type, method will end – Xorty Jul 07 '10 at 12:51
-
this is similar to the first answer, except you're using return instead of simply letting the run() method exit. And yes, you can just use return; and that will exit from a void method – Richard Jul 07 '10 at 15:25
-
Ah, I misunderstood. I thought you wanted to return a value from the run and do something (whatever) with that. Of course, using return to quit the method is perfectly possible. – Bart van Heukelom Jul 07 '10 at 22:39
Make a volatile boolean stop
somewhere. Then in the code that runs in the thread, regularly do
if (stop) // end gracefully by breaking out of loop or whatever
To stop the thread, set stop
to true
.
I think you must do it manually this way. After all, only the code running in the thread has any idea what is and isn't graceful.

- 43,244
- 59
- 186
- 301
-
22Note that you either need to use locking or make the field volatile to make sure the reading thread sees changes from the writing thread. – Jon Skeet Jul 07 '10 at 12:20
-
@Jon Skeet: Yes, that would be better. Out of curiosity though, how long would the stopping approximately be delayed if the field is not volatile? – Bart van Heukelom Jul 07 '10 at 12:39
-
6
-
@Jon Skeet: Really? Wouldn't that mean that in a theoretically correct multithreaded program many fields need to be volatile? I'll need to read up on this some more when I get the chance. – Bart van Heukelom Jul 07 '10 at 12:52
-
@Bart: Normally if a multi-threaded program needs to share mutable state, it will use locking instead of volatility. Sharing immutable state is much simpler, of course. – Jon Skeet Jul 07 '10 at 12:59
-
1@Bart: using a non-volatile boolean, the following loop while(!stopped){ doStuff();} can be optimized to if(!stopped)return;while(true){doStuff();} by the compiler – mpm Jul 07 '10 at 15:13
-
I'm confused, the answer says volatile, and it doesn't say it was edited. Where's the mistake? – nairbv Sep 19 '12 at 03:15
-
You need to send a stop-message to the Thread and the Thread itself needs to take action if the message has been received. This is pretty easy, if the long-running action is inside loop:
public class StoppableThread extends Thread {
private volatile boolean stop = false;
public void stopGracefully() {
stop = true;
}
public void run() {
boolean finished = false;
while (!stop && !finished) {
// long running action - finished will be true once work is done
}
}
}

- 113,398
- 19
- 180
- 268
-
I edited my answer but will go and find out, why it applies here - in your answer, I thought, it had to be volatile just because you didn't mention a method and it looked like, the `stop` field had to be accessed directly. – Andreas Dolk Jul 07 '10 at 12:44
-
1I've wondered about the volatile keyword before and (without trying to advertise my own question :) ), here's a few answers on it: http://stackoverflow.com/questions/106591/do-you-ever-use-the-volatile-keyword-in-java – Richard Jul 07 '10 at 15:27
-
Can you explain how it is better than using the java `interrupted` flag intentionally devised for this case? – Val Oct 03 '13 at 08:28
For a thread to stop itself, no one seems to have mentioned (mis)using exception:
abstract class SelfStoppingThread extends Thread {
@Override
public final void run() {
try {
doRun();
} catch (final Stop stop) {
//optional logging
}
}
abstract void doRun();
protected final void stopSelf() {
throw new Stop();
}
private static final class Stop extends RuntimeException {};
}
A subclass just need to override doRun() normally as you would with a Thread, and call stopSelf() whenever it feels like it wants to stop. IMO it feels cleaner than using a flag in a while loop.

- 2,479
- 1
- 20
- 26