• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

best way to kill ?

 
Ranch Hand
Posts: 282
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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).
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
author
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
??? Why this business with an isRunning flag while there is a perfectly standard way to interrupt a thread?
- Peter
 
Ranch Hand
Posts: 1170
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Ranch Hand
Posts: 1953
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 1170
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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).]
 
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 1953
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 1170
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 1170
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 1170
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 1953
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 1953
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 532
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 1170
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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).]
 
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Peter den Haan
author
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 68
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Every plan is a little cooler if you have a blimp. And a tiny ad.
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic