Sunday, October 30, 2011

How to Stop Thread in Java Code Example

Thread is one of important Class in Java and multi-threading is most widely used feature,but there is no clear way to stop Thread in Java. Earlier there was a stop method exists in Thread Class but Java deprecated that method citing some safety reason. By default a Thread stops when execution of run() method finish either normally or due to any Exception.In this article we will How to Stop Thread in Java by using a boolean State variable or flag. Using flag to stop Thread is very popular way  of stopping thread and its also safe, because it doesn't do anything special rather than helping run() method to finish it self.


How to Stop Thread in Java


How to Stop Thread in Java Tutorial Example
As I said earlier Thread in Java will stop once run() method finished. Another important point is that you can not restart a Thread which run() method has finished already , you will get an IllegalStateExceptio, here is a Sample Code for Stopping Thread in Java:








Sample Code to Stop Thread in Java



    private class Runner extends Thread{
    boolean bExit = false;
  
    public void exit(boolean bExit){
        this.bExit = bExit;
    }
  
    @Override
    public void run(){
        while(!bExit){
            System.out.println("Thread is running");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(ThreadTester.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
    }
}
    
    

Should we make bExit Volatile
Since every Thread has its own local memory in Java its good practice to make bExit volatile because we may alter value of bExit from any thread and making it volatile guarantees that Runner will also see any update done before making bExit.

That’s all on how to stop thread in Java , let me know if you find any other way of stopping threads in Java without using deprecated stop() method.


Related Java Multi-threading Post:

13 comments :

Aman Mohla said...

I have been wondering why isn't there a method to kill a waiting, sleeping or a non running thread. Is there anyway we can do that?

Paul W. Homer said...

The reason you can't just stop a thread is actually fairly simple. What if it's allocated resources, and is in the middle of work? If you do a hard stop, that may just leave a lot of stuff hanging. So, instead you basically send it a message and it stops at it's own convenience (if implemented properly). Basically they pushed back that part of the behavior to the programmers.

Javin @ secrets of generics in Java said...

Thanks for your Comments Paul. but isn't it Java's main idea is to do common stuff by JVM and not by programmer e.g. Memory Management is done by Garbage Collection , they can easily provide a shutdown or kill thread like method, isn't it ?

Anonymous said...

Another way to stop a running thread is to set the thread object as null.

Pankaj

Javin @ class in Java said...

Hi Pankaj, I doubt that will work, simply setting thread object null will not stop thread in my opinion, have you tried it ?

Anonymous said...

How to Kill a thread or how to stop a thread is just waste of time you can do better job with Executor framework, let the framework start and kill thread rather than you.

Anonymous said...

How about using interrupt and check the interrupt flag on the thread and stop if it has been interrupted? If the thread is in a non-blocking state, it will ignore it. However, if it reaches a blocking call such as wait/sleep it will throw an InterruptedException.

chubbard said...

You cannot simply kill a thread because if it owns any locks (ie if it's in the middle of a synchronized block when you kill it) those locks won't be released leaving your program in a state where it will certainly deadlock. Its an OS thing, but that's why. While the example provided here works and adding volatile, blah, blah, blah. I don't think it really gives any insight how threading works in the JVM.

Threads in the JVM work on the interrupted model. You can't force a thread to stop for the reasons stated above, but you can request a thread to be interrupted. Its up to the author of the thread to respond to that request.

Any thread can request any other thread to shutdown by simply calling: threadIWantToKill.interrupt(). That sets the interrupt flag on it. When that thread enters a blocking call or tries to wait on a lock like Thread.sleep(), or Object.wait() an InterruptedException will be thrown. That's why you shouldn't try catch and ignore those. A descent run() loop should be:

try {
while( !Thread.currentThread().isInterrupted() ) {
// do your business here
}
} catch( InterruptedException ex ) {
logger.info("Thread shutting down requested.");
} finally {
// clean up any mess here.
}

From the comments on this thread its clear most Java developers have no clue about how to cleanly stop threads.

chubbard said...

Oh an the Executor framework suggestion doesn't shield you from the rules of threading either. You can still get an InterruptedException thrown inside the Runnable you created because ITS RUNNING IN A THREAD. If you swallow that InterruptedException you're going to prevent the Executor framework from shutting down.

Javin @ String split Java said...

@chubbard , Thanks for your comment.I guess that's why Stop() method of Thread was deprecated because it leaves locks open. Interrupting is also a possible solution.

Rick said...

I guess killing a thread has same meaning as stopping a thread as you can not restart a thread which is stopped in java. natural way of stopping thread is let thread come out of its run() method which as suggest can be used with an exit flag, make sure it should be volatile to prevent compiler or JVM optimization in terms of caching or reordering. here is an example of stopping thread in natural way. By the way if you are working in a project I suggest using Executor framework. Executor can better manage thread and free application code from doing thread management. ExecutorService provides shutdown() method to stop Executors which will stop all running thread on pool. It also provides query method to see if Executor has been terminated or still shutting down.

Anonymous said...

Rick, you said that ExecutorService provides thread management. On the other hand, the same ExecutorService do not provide any option to stop a thread! You can only shutdown the service which stops all threads. I also read about using Future to stop threads, any ideas!

Anonymous said...

ExecutorService returns the handle to each thread in the reference of Future. Calling Future.cancel(true) can stop the running thread.

Post a Comment