This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes best way to kill ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "best way to kill ?" Watch "best way to kill ?" New topic
Author

best way to kill ?

Amit Agrawal
Ranch Hand

Joined: Aug 23, 2001
Posts: 282
what is the best way to kill a thread ? ok, I have few child threads which don't hold any resources but are user threads (Actually Timer threads).
I want to kill all of them at some point so that my parent thread can end. since stop() is Deprecated, what could be the best way to kill a tread.
I was looking at destroy() method but it has not been implemented so far (jdk1.4 beta).
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Amit
You could but the code in the run method in a loop that tests a variable. When it is time to kill the Thread set the variable to false, then the loop exits and the Thread dies.
If you need a code example let me know

------------------
Dave
Sun Certified Programmer for the Java� 2 Platform


Dave
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
First, investigate whether setDaemon() would be of any use. Second, if they're not daemon threads then I would suggest using interrupt(), it's what it is for.
- Peter
hard coder
Greenhorn

Joined: Sep 21, 2001
Posts: 5
Hello Amit.
Try this
class mythread extends Thread
{
private boolean isRunning = false;
public void startMyThread()
{
isRunning = true;
try
{
start();
}
catch( IllegalThreadStateException itse)
{
// Forget it
}
}
public void run()
{
while (isRunning)
{
// do stuff
}
}
public void stopMyThread()
{
isRunning = false;
}
public boolean isRunning()
{
return isRunning;
}
};
class Caller
{
psv main()
{
MyThread thread = new MyThread();

// Code to start thread
thread.startMyThread();

// Code to wait on thread, if required...(for instance when you want the thread to complete at least one run; you will also have to set the isRunning var to false at the end of the loop in the run method then.)
while(thread.isRunning())
{}

// To stop the thread
thread.stopMyThread();
}
}
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
??? Why this business with an isRunning flag while there is a perfectly standard way to interrupt a thread?
- Peter
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Originally posted by Amit Agrawal*:
what is the best way to kill a thread ? ok, I have few child threads which don't hold any resources but are user threads (Actually Timer threads).
I want to kill all of them at some point so that my parent thread can end. since stop() is Deprecated, what could be the best way to kill a tread.
I was looking at destroy() method but it has not been implemented so far (jdk1.4 beta).

This is what daemon threads are for. If you want them to end with yourprogram, they should not be user threads. The best way to end any thread will be to let its run method come to an end. Ask the thread to end itself, don't try to force it to stop.
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
Dr. Haan
I might missing something. How could Thread.interrupt() equivalent to kill the Thread? Can you give a simple example?
My answer is equivalent to Dave or "hard coder" (probably not a proper name in JavaRanch). I've an answer for a similar question at http://www.webappcabaret.com/javachina/faq/05.htm#thr_b18
Take a look!
However, if i change my code to use t1.interrupt() the result would be t1 will never stop. Can you explain a little more?
<pre>
class T extends Thread {
boolean runflag = true;
public T(String name){
super(name);
}
public void run() {
int i = 0;
while (runflag) {
System.out.println(getName() + ": " + i++);
try
{
sleep((int)(400*Math.random()));
}
catch (InterruptedException e) {
}
}
System.out.println(getName() + " is stopping.");
}

void setRunFlagFalse() {
runflag = false;
}
public static void main(String args[]) {
T t1=new T("t1");
T t2=new T("t2");
T t3=new T("t3");
t1.start();
t2.start();
t3.start();
try
{
// let three threads run
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
// stop them
t1.interrupt();
//t1.setRunFlagFalse();
t2.setRunFlagFalse();
t3.setRunFlagFalse();

// do something else
// lots of code...
}
}
</pre>
Thanks!
Roseanne

SCJD Study Group has been moved to http://www.developergroup.org/
[This message has been edited by Roseanne Zhang (edited October 05, 2001).]
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Originally posted by Roseanne Zhang:
[b]Dr. Haan
I might missing something. How could Thread.interrupt() equivalent to kill the Thread? Can you give a simple example?

B]

interrupt will only wake your thread when its doing something "interruptable" like sleep() or wait(). Otherwise interrupt will do nothing. Once your thread is interrupted and the InteruptedException gets fired, you are not doing anything with the exception and you are just staying in the while loop. You could set some variable in the catch block, or maybe even a break; there. But it really is NOT the way to stop a thread as I indicated above, let the run method come to a gracious end.
[This message has been edited by CL Gilbert (edited October 22, 2001).]
Jim Baiter
Ranch Hand

Joined: Jan 05, 2001
Posts: 532
But runflag has package scope. Couldn't another class in the same package change the runflag to false thereby causing the run method to complete and the thread to terminate?
Originally posted by Roseanne Zhang:
[b]Dr. Haan
I might missing something. How could Thread.interrupt() equivalent to kill the Thread? Can you give a simple example? ...


[This message has been edited by Jim Baiter (edited October 15, 2001).]
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
1) Jim, You are right! My code is just for playing, however, it should be public.
2) CL, you're right too. I read the other post of Peter Haan, and now understand what he meant by using interupt. I still don't agree with him since interrupt is too generic, it can be set and unset for many reasons, not exclusively for kill. My runFlag is better.
3) Jim and CL, why you guys wasted so much Paul/JavaRanch's precious disk space to requote my post? I'm not that important. Please use the little icon with a pencil in your post to delete them. Thanks!
Roseanne
[This message has been edited by Roseanne Zhang (edited October 06, 2001).]
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Originally posted by Roseanne Zhang:
2) CL, you're right too. I read the other post of Peter Haan, and now understand what he meant by using interupt. I still don't agree with him since interrupt is too generic, it can be set and unset for many reasons, not exclusively for kill. My runFlag is better.
Roseanne, to my mind it depends. If you need to do something with a Thread that should interrupt what it is currently doing and make it do something else, you should use interrupt(). That's what it is for.
If there are multiple things you may want a thread to do, then a flag is the only way forward. Set the flag, call interrupt() to wake up the thread from whatever it is doing. It will read the flag and do what it's supposed to do.
If there's only one thing you ever want a thread to interrupt its work for - in this case: die - then a flag is, in principle, superfluous. You could perhaps argue that it should be retained nevertheless for clarity. But if clarity is the issue then a much better solution would be to create a proper abstraction of the whole thing and provide a management interface with a killThread() method. Behind the scenes, that killThread() method may simply be calling interrupt(); this is then a hidden implementation detail and the "too generic" argument no longer applies.
- Peter
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Originally posted by Peter den Haan:
Roseanne, to my mind it depends. If you need to do something with a Thread that should interrupt what it is currently doing and make it do something else, you should use interrupt(). That's what it is for.
If there are multiple things you may want a thread to do, then a flag is the only way forward. Set the flag, call interrupt() to wake up the thread from whatever it is doing. It will read the flag and do what it's supposed to do.
If there's only one thing you ever want a thread to interrupt its work for - in this case: die - then a flag is, in principle, superfluous. You could perhaps argue that it should be retained nevertheless for clarity. But if clarity is the issue then a much better solution would be to create a proper abstraction of the whole thing and provide a management interface with a killThread() method. Behind the scenes, that killThread() method may simply be calling interrupt(); this is then a hidden implementation detail and the "too generic" argument no longer applies.
- Peter

I disagree. Interrupt is only for those few things I specified above. If you are off processing packet data or anything that the thread is not wait() or sleep() then interrupt will do nothing. In the wait() case, you should be able to notify the thread, in the sleep case, you will have to interrupt it. But that is the only case I can think of. Interrupt does not stop the thread, I hope you see that point.
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Originally posted by Jim Baiter:
But runflag has package scope. Couldn't another class in the same package change the runflag to false thereby causing the run method to complete and the thread to terminate?

Yes. I guess if its some rogue class with Artificial Intelligence

Seriously though, you just cant make the software idiot proof, when your the idiot, hehe. I couldnt resist that one. But no offence, you could make accessor methods and do other things, but you just can't prevent mistakes. You can make them appear obvious though and get a little help from the compiler. And more to the point, if you already have access to the Thread, getting access to its variables wont offer you much more ability in the way of destructive behavior.
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Originally posted by CL Gilbert:
If you are off processing packet data or anything that the thread is not wait() or sleep() then interrupt will do nothing.
Taken at face value, this is incorrect. It will (as you well know) set the interrupted flag which can be queried using the isInterrupted() or interrupted() methods. The flag exists specifically so you can check it inside tight loops that won't otherwise be interrupted. For instance, you could simply incorporate in a suitably frequently executed spotand handle the exception at the appropriate level. If you've got any wait()s or sleep()s this nicely unifies the way you handle interrupts.
Any code that duplicates a facility already present in the Java libraries is simply wrong (unless the code predates said facility of course ). Wrong because it costs money to write, costs money to maintain, is likely to contain more bugs and makes the application harder to read. If I see code that basically does what the interruption facility does, although hardly a significant bit of duplicated code, I get the refactoring itch.
In the wait() case, you should be able to notify the thread
That's an oversimplification - notify() and interrupt() are completely different means to completely different ends. Most likely, notify() is used to coordinate the normal flow of operation within a class - a producer/consumer pattern, whatever. Interrupt() on the other hand is typically used to break the normal flow of operations. Code such asmixes up the normal logic with a special case (!isRunning) and is - especially if you need to break out of several layers of blocks and method calls - a more difficult to understand than using an interrupt and letting the exception propagate up to the level where you can catch it and act upon it (in this case, you can catch it just inside the run() method and simply allow control to drop out of run() to stop the thread).
But that is the only case I can think of. Interrupt does not stop the thread, I hope you see that point.
That's obvious, but does not mean that it isn't a fine way to implement the required thread-stopping feature. By the way, if you scroll up in the thread, you'll see that I recommended daemon threads as a first choice.
- Peter

[This message has been edited by Peter den Haan (edited October 08, 2001).]
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Peter, I just think using interrupt to "stop" the thread is not correct. Interrupt does what it intends to do, that is to interrupt those operations which are interruptable. If you want to extend it to also cause the thread to end its life, thats fine, but to me this is not a natural extension. One should not have to throw an exception to end a threads life.

In my opinioin this is how you handle manipulating a running thread. Interrupt has its place, but I don't think this is it.


[This message has been edited by CL Gilbert (edited October 09, 2001).]
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
Using general purpose Thread.interrupt() to kill a thread is absolutely a BAD idea, since your create a side effect for the general purpose method, and invite unaware programmer to make mistakes since they only read Sun's Thread javadoc.
Never do this kind of stunt, please!
Please follow KISS rule in your code, Keep It Simple and Stupid, or Keep It Simple and Straight foward. Do your boss and current/future coworkers a favor please!
There is one exception, if you're the boss, you can do and ask your employees do whatever you want. If they do not follow your order, fire them!
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Wow, a religious discussion. Cool
Thread.interrupt() is meant to ask a thread to stop what it's doing straightaway and do something else.
Killing a a thread means that you ask it to stop what it's doing straightaway and die.
The second sentence above is a special case of the first sentence.
If you accept these premises, perhaps conditionally, it follows that Thread.interrupt() may have an essential role to play in the operation of killing a thread. Indeed, in the presence of sleep() or wait() calls you would be hard pressed to argue otherwise. Taking that as a starting point, there are a few things to note.

  • If you are using interrupt() to wake the thread from a possible wait() or sleep() when it needs to do something, then you must be catching the exception at some level and perhaps examining flags to figure out what needs to be done. It only makes sense to let the interrupt propagate all the way up to the appropriate level (which is dictated by the problem rather than taste). Given this, the interrupt flag is the flag to poll inside loops as well; otherwise, you're stuck with two different patterns of interrupt handling, probably duplicate code, and a source of subtle bugs if you forget to clear the interrupt flag.
  • When there is only one operation you need to interrupt the thread for, you can in principle dispense with flags.
  • Whether interrupting (killing, &c) a threaded operation involves using Thread.interrupt() or not is actually an implementation detail of the class(es) that extend or are run by the thread, and is best hidden by a method anyway.

  • There are provisos, of course. If you don't want to kill your thread, but to shut it down gently, you probably don't want to interrupt sleep() or wait() operations. That changes the story completely, and I would not advocate abusing Thread.interrupt() in these situations (although it can be done if you're perverse enough), the concept simply wouldn't fit and it would be as misleading as you say.
    - Peter

    [This message has been edited by Peter den Haan (edited October 11, 2001).]
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Originally posted by CL Gilbert:
Peter, I just think using interrupt to "stop" the thread is not correct. [... Thread class with 3 states ...]In my opinioin this is how you handle manipulating a running thread. Interrupt has its place, but I don't think this is it.
I see your point; actually, I don't think we're quite as far apart as it seems.
Given that the example you gave has three different states, I would use a flag in exactly the same way. However, calling endThread() while the flag is in the PAUSE state would not effect the desired state transition; it seems to me that an interrupt() is required in endThread(). Now, imagine that "// do normal stuff" involves time-consuming operations that you do not want to finish normally if endThread() is called. In other words, you want to interrupt(!) the normal stuff. The most natural implementation would be to test Thread.interrupted() in the "normal stuff" too. That way, you make the normal stuff an "interruptable activity" in a way that appears quite legitimate to me.
I am not proposing that interrupt() be used blindly. For instance, a pauseThread() method would be unlikely to use it; you would probably want normal things to run their course before effecting the pause.
Could it be simply a difference in our interpretation of what the original poster meant by "killing a thread"? The reference to Thread.stop() made me think of making the thread stop what it's doing, whatever it's doing - interrupt it and quit run() (interrupt as in English, not necessarily as in Java Thread.interrupt(), although of course the word is deliberately suggestive ).
- Peter
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
Peter,
To me, at the least, what you said just proved I was right.
Stop is general, stop life is special. General includes special, but general does not imply special. If it does, it is a side effect. If stop sign on the street does also imply stop life, that would be really bad!!!
However, since you metioned religion, I pay respect to all religions, including yours, of course. We'd better agree to disagee on this problem. I'll quit and stop right here.
Have a good night, oh, wait a minute, on your side of the world, good morning!!!
Roseanne
Jim Baiter
Ranch Hand

Joined: Jan 05, 2001
Posts: 532
Here's the Sun recommendation on the JDC - http://developer.java.sun.com/developer/qow/archive/154/index.jsp
[This message has been edited by Jim Baiter (edited October 21, 2001).]
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

In the end, suggesting to stop a thread with interrupt is in any way impossible. As I said, it only has noticable effect when you are in an interruptable state. We have not been given by Sun the ability to "interrupt". This interrupt generally interrupts naive calls that we have no other way to get at. If you think you can just break your thread at any arbitraty point in its life and ask it to stop, I say go ahead. As soon as you hit a dual cpu computer or even long before you will be debugging your interrupt routine till the cows come home. Why? because you are specifically requesting unpredictable behavior.

If you want a thread to be "interruptable" make it check a variable every .5s or faster depending on the response time you seek.

Update: Now that I have read Peter's information in another thread, I too believe we are close on this. I say you need to check a variable every .5s or so, turns out this is in effect what sleep() and wait() are doing. They are checking the interrupt flag. So Yes I agree you can encapsulate this completely in the interrupted methodology and consistently mimmic the baked in sun performance...


[This message has been edited by CL Gilbert (edited October 23, 2001).]
dan moore
Ranch Hand

Joined: Nov 04, 2001
Posts: 68
w.r.t. using setDaemon(false) on the threads.
in my religion it is somewhat unholy to artificially extend the natural life of a thread by not killing it when its time is up.
my understanding is that these threads continue to run until the JVM exits - in many contexts this could be rather undesirable. or so my priest says. and my doc.
cheers, dan.


dan moore, infomatiq ltd.<br />email dan@infomatiq.co.uk<br /><a href="http://www.infomatiq.co.uk" target="_blank" rel="nofollow">http://www.infomatiq.co.uk</a>
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
A JVM won't exit unless all non-daemon threads have stopped executing. The only thing setDaemon(true) does is make sure that the fact that the thread is running does not prevent the JVM from exiting. It does not give the thread an artificially longer lifetime.
One common example of a daemon thread is the spellchecker thread in a word processor. You want to keep it alive permanently because starting up a new thread every time the user finished typing a word is too costly. Yet you don't want a running dictionary search prevent the application from exiting.
About thread lifetime: keeping threads alive for long periods of time is more common than you might think. Because starting up a thread is a costly task, most serious servers maintain a pool of permanently running threads. (Of course, those threads spend their time in a wait() statement until there's something to run for them). Not that I'm implying these are necessarily daemon threads - you probably want to implement some form of cleanup for the tasks run by the threads, you don't want the JVM to just quit on you.
- Peter
dan moore
Ranch Hand

Joined: Nov 04, 2001
Posts: 68
sorry, yes, setDaemon(true) is what i meant.
the point i was trying to get clarified is:
agreed that daemon threads will not prevent JVM exiting, i.e. that until that JVM exits those threads (if not explicitly killed) will continue to hang around. but in certain circumstances, say if JVM is running more than one app (never done this, using different class loaders i heard), couldn't this be quite bad? my understanding is that a general practice of leaving all your helper threads around as daemon threads would then produce a load of living garbage.
thanks for replies,
cheers, dan.
 
GeeCON Prague 2014
 
subject: best way to kill ?