File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes How to stop a Thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "How to stop a Thread" Watch "How to stop a Thread" New topic
Author

How to stop a Thread

Sam Samson
Ranch Hand

Joined: Oct 08, 2011
Posts: 61

Hi

How can I stop a Thread from running? I've read in the JavaGuide, that I could set the Thread reference to null.
What's happening if I do that? Will the running thread immediately stop, no matter where he actually is in the run() method?

And what's the difference between setting the Thread reference to null and using the interrupt() method?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18531
    
  40

Sam Samson wrote:Hi

How can I stop a Thread from running? I've read in the JavaGuide, that I could set the Thread reference to null.
What's happening if I do that?
Will the running thread immediately stop, no matter where he actually is in the run() method?



If you set your Thread reference to null, then that reference can no longer be used to access the thread object. The action will have absolutely no effect on the running thread.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18531
    
  40

Sam Samson wrote:And what's the difference between setting the Thread reference to null and using the interrupt() method?


If you call the interrupt() method, then it will have an effect on the running thread. If the thread is calling something that is interruptable, then it will return with an exception. Otherwise, it will just set a flag, which the thread can check to determine that it has been interrupted.

In either case, it is the responsibility of the interrupted thread to handle the exception, or to check and deal with the flag. It doesn't just magically stop the thread in its tracks, and clean up the mess.

Henry
Sam Samson
Ranch Hand

Joined: Oct 08, 2011
Posts: 61

Henry Wong wrote:
If you set your Thread reference to null, then that reference can no longer be used to access the thread object. The action will have absolutely no effect on the running thread.
Henry


So why in the JavaGuide this method is mentioned?
Tim Moores
Rancher

Joined: Sep 21, 2011
Posts: 2408
Because setting the reference to null is used as a "marker" that the thread should stop running. You'll see in the code that it checks the value of the reference, and will stop if it changes. But that's because the application's code checks for that, not because the JVM or Java threads generally work that way. Personally, I think it's a rather hackish way of doing things.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4343
    
    8

In general setting the Thread reference to null has no effect. That article describes a mechanism where the Thread reference is used within the Runnable's run() method to determine whether it should continue or not. In that case, yes, setting it to Thread will do something, because of the way the rest of the code is written. I've used a similar approach in the past using a boolean flag instead.

The way to make a Thread end cleanly is to make the run() method exit normally, and the way they describe is one way of making that happen.
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12761
    
    5
If you check the JavaDocs for java.lang.Thread you will see methods such as stop(), suspend() and resume() that were in Java 1.02 and you will see these methods were deprecated in subsequent versions because they led to unpredictable results. See the explanation in the stop method JavaDocs.

Generally you have to be very careful to provide for a graceful exit from the run method.

Bill
Sam Samson
Ranch Hand

Joined: Oct 08, 2011
Posts: 61

Ok, I've understood that with the marker, but...



what should I do If I don't have a loop in my run()? In the example above, the sleep() doesn't cause a thread to start again from line1, right? If yes, that sleep() only add some confusion because it has nothing to do with how to stop the thread.
Ranganathan Kaliyur Mannar
Bartender

Joined: Oct 16, 2003
Posts: 1076
    
  10

Sam Samson wrote:what should I do If I don't have a loop in my run()?

That would mean, there is only a single sequence of action in the Thread. So, what you are trying to ask is: I have only a single sequence of action in my Thread which takes long time to execute. So, how do we exit on recieving a signal?
I think using the Thread.interrupted() call to check if the Thread has been interrupted is the best way. And in this case, this will have to be repeated at more than one place, like:
step 1: 5 lines of code
check if interrupted
step 2: 7 lines of code
check if interrupted

and so on...Note that, the new concurrency utilities also use this mechanism only. For ex., 'shutdownNow' method in the ExecutorService just calls Thread.interrupt on all the threads it started. So, checking for the interrupted flag is propably the best way.


Ranga.
SCJP 1.4, OCMJEA/SCEA 5.0.
Sam Samson
Ranch Hand

Joined: Oct 08, 2011
Posts: 61

Ok, I keep that in mind.

And starting a second thread that is checking if the marker-variable is null or not and notifies the other thread is a bad idea or doesn't work at all?
Martin Vajsar
Sheriff

Joined: Aug 22, 2010
Posts: 3606
    
  60

Sam Samson wrote:And starting a second thread that is checking if the marker-variable is null or not and notifies the other thread is a bad idea or doesn't work at all?

The marker-variable would have to be set to null by someone, right? In that case, that someone can invoke Thread.interrupt() directly, you don't need another thread just to do so. It could look like this:

The hard part is to distribute the check for interrupts throughout the non-loopy code. I was actually once solving such issue myself, and I wanted to make sure the thread will react to interrupt in a timely fashion (say, in a second). I had a method that checked for the interrupt flag (and threw an InterruptedException when it was set), and this method also checked how much time has passed since the last call. If it was more than a second, the call was logged (logging a stack trace might be very useful in this context), and I was able to infer from the log which part of code needed to call the check routine more often. Assuming I got to read the log, that is
Istvan Kovacs
Ranch Hand

Joined: May 06, 2010
Posts: 100
Java Concurrency In Practice devotes a complete chapter to shutting down. I highly recommend the book.
Basically, as the others have suggested, you could use interrupt() and handle InterruptedException or check the flag (but be sure to check the difference between interrupted() and isInterrupted()).
You could also use a volatile boolean field (say, keepRunning) that you check in a loop.
Or, if you read jobs from a queue, you could insert a 'poison pill', a special job instance that you do not execute, but use its occurrance as a signal to stop.
If your thread is stuck reading from a socket, closing the socket is the only way to wake it up (it will not react to interruption). For NIO, use InterruptibleChannel. With java.nio.channels.Selector, use wakeup(). If the thread is waiting to enter a synchronized block, you can do nothing; converting code to use explicit Locks allows for interruption (but you have to be careful with exception handling).
Ranganathan Kaliyur Mannar
Bartender

Joined: Oct 16, 2003
Posts: 1076
    
  10

Martin Vajsar wrote: If it was more than a second, the call was logged (logging a stack trace might be very useful in this context), and I was able to infer from the log which part of code needed to call the check routine more often.

This is a sensible and practical idea...thanks!
 
Consider Paul's rocket mass heater.
 
subject: How to stop a Thread
 
Similar Threads
Can't catch Window Close event when trying SocketServer trying to accept connections
Stop a thread in ThreadPoolExecutor
Garbage Collection and Threads
Removing objects (Threads)
How to kill a user thread forcefully?