how to stop a thread safety ?

hi all~

i start running a thread by calling myThread.start method but there seems no something like myThread.stop() or myThread.die to stop it eternally, of course i could do this by setting the thread to null(like the code below):


myThread = null;

and is this the only way we could stop the running thread ?

regards~

Set a flag to tell the thread to exit the run() loop

Like:


while (isRunning) {
… do thread stuff
}

public void endThread() {
isRunning = false;
}

tks, and another problem comes, myThread.sleep is handy to pause the running thread, however what if we do not know exactly time thread sleeping ? although passing a very big number to myThread.sleep is helpful i still prefer the way to stop current thread simply(better if we could run it from the point it stops), any suggestions ?

thanx in adv~

Like:


while (isRunning) {
if(zombified)
… sleep for like 5 msecs
else
… do thread stuff
}

public void endThread() {
isRunning = false;
}

public void setZombie(boolean zombified) {
this.zombified=zombified;
}

However, doing something like that makes rarely sense. I can’t think of anything actually :slight_smile:

You can use myThread.wait() and myThread.notify()

WARNING: setting mythread = null does absolutely nothing unless you have a loop that starts “if( mythread != null)”. I say this because I’ve seen lots of cases where newbie coders thought that setting it to null magically stopped the thread itself.

You are “supposed” (required) to add an:

myThread.interrupt();

after you’ve nulled or falsified the boolean that the thread is spinning on.

Personally, ignore the whole [in whiny voice] “you’re all too stupid to be allowed teh Supreme Power of thread.stop” argument, and just use Thread.stop most of the time.

It’s extremely difficult to create race conditions in java threads with this method (I’ve met very few people who’ve managed it), despite it being the “reason” sun gave for telling people not to use the method.

Whilst I like the idea of asking a thread to stop, then kicking it to tell it to “stop now”, without thread.stop you STILL have NOT stopped it - I’ve seen threads faff about for seconds still not stopping, so in defensive code I tend to come back 1 second later and call Thread.stop() for good measure: most of the time when you are stopping a thread you ABSOLUTELY MUST stop it NOW; not “soon”, but NOW. Sun has provided no condoned method for this.

It’s stupid to recommend usage of Thread.stop() when Sun tells you not to use it. If Thread.interrupt() is not sufficient for your application I would say you have a bad design.

Thread.stop() has been deprecated for quite some time, and I doubt it will go away any time soon unless there’s a good alternative.
However, IF you feel the need to use it, you should think very very carefully about it, and you should definitly feel bad about writing code that bad.

One example of why it’s bad is that it effectively causes the thread to throw an exception (Actually, an error; ThreadDeath) at a random point in your code.
For example, calling thread.stop() while the thread happens to be in the following method can REALLY mess up your program:

public synchronized switchBuffers()
{
ByteBuffer tmp = buffer0;
buffer0 = buffer1;
// If the thread happens to be stopped here, you’re screwed.
buffer1 = tmp;
}

Of course, there are ways to work around that, such as catching ThreadDeath(*) or synchronizing over some lock before calling thread.stop()(**), but in general you’re just potentially shooting yourself in the foot by adding exceptions that can be thrown at random.

(* Don’t.)
(** This is probably about as hard to implement properly as it would be to stop the thread the “correct” way)

I can’t see a good reason why Thread.stop() should have been deprecated. The implementation appears to simply proved too much of a headache for Sun’s native code engineers. What’s so hard about getting a Java thread to release any locks it’s holding, or notifying all waiters of the event when it happens?

Cas :slight_smile:

[quote]I can’t see a good reason why Thread.stop() should have been deprecated.
[/quote]
If you want Thread.stop() to work while the thread is in native code, then on Windows you would have to use the ThreadTerminate function which has a whole catalog of warnings attached including potentially leaving the Windows kernel in an inconsistent state for that process!

If we don’t allow that, then you still have the problem of damaged objects. Any object which needed synchronization to maintain consistency could now be in an inconsistent state if it was being manipulated by the terminated thread at the time. To avoid this you would have to either have some means of marking objects as potentially damaged (and your code would have to check that), or you don’t allow Thread.stop() to take effect until all locks have been released (which would often mean that the code didn’t stop ever).

Although deprecated, I think it should be retained for those cases when nothing else will do. The warnings attached mean that developers should be aware of the potential complications.

The java docs sum it up nicely :slight_smile:
http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

Looks like this i a topic that interests lots of people. And it sounds like the Thread.stop() was made by a mistake :wink:

The code is not really “bad”; I know what I’m doing: I really need the thread to actually stop and - like the good programmer I am - any object corruption that could happen is going to be constrained to the things that are killing the thread because they’re dieing themselves (for example) - so it really doesn’t matter.

The funny thing is, with good multithreaded code, by the time you have made the decision to stop a thread, you normally don’t care if things are corrupted, so long as they are constrained towhat the thread is accessing.

…although I think that’s scaremongering; I’ve used thread.stop for many yeasr without problems.

if Sun provided us with a decent way to stop threads which were equally powerful (and note that there are several places where a thread will block and interrupt will do nothing, but stop WILL - so you have no other choice) then I would be more inclined to use it.

I didn’t mean YOU you. I meant “one”.
Like “one should avoid eating gravel” or “one should avoid anybody selling a ‘solution’”. :wink:

I’ve used Thread.stop myself a few times, mostly as a way to stop out of control third party plugins, where I actually stop an entire ThreadGroup. My point was that you (“one”) should avoid using stop unless you (“one”) is sure you (“one”) needs to.

Why are we talking about Thread.stop() anyways? There is no need to use it.

If you you think you need it, you are doing something wrong. That is why it is ok to depricate it… it shouldn’t have been in the API and it isn’t needed. You would have to have a pretty bad design to consider using it anyway.

Here is something to consider if you really think its a good idea to use it:

“ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted ADDED: nor does the developer. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.”

This may be less of a problem for a game where it isn’t going to run for days anways, but it could still bite you bad when a user reports strange, unreplicable errors. If you are writing a game server or something else long lived, it will come back to bite you, but you may never see it until you get a bug report that causes you to shake your head for a week. Do it right from the start.

If thousands of programs can be written for all manner of problems, without it…you can too :slight_smile:

I’m fairly sure it was deprecated because it’s a very bad idea to use it, but there really are situations where you need it. Trust me. :wink:

[quote]I didn’t mean YOU you. I meant “one”.
[/quote]
Ah! OK :slight_smile:

[quote]Why are we talking about Thread.stop() anyways? There is no need to use it.
[/quote]
Trust me on this: you just don’t have enough experience with java to have come across any of the situations yet where you HAVE to use it.

Re-read my previouse posts: thread.stop stops the thread; NOTHIGN ELSE DOES.

For instance, as SLJ put it: “for when you absolutely gotta waste every *********ing one of em!”

I already explained why that isn’t actually a problem at all in many cases…

Actually, the only thing that stops a thread is the thread returning from the run method. Thread.stop just causes the thread to throw a ThreadDeath error, and if that isn’t caught, the thread will stop once it’s thrown out from the run method.

But that’s just nit-picking. :wink:

Yeah, I don’t really get what’s wrong with the ThreadDeathError scenario anyway. I mean, Errors can get thrown anywhere by all sorts of weird things, so why was it suddenly a big deal in Thread.stop()? And the answer is that native code resource locks are a bugger to deal with, and that’s Sun’s fault with JNI.

What Thread needs is a shutdown hook.

Cas :slight_smile: