Reputation: 26455
A quote from "Effective Java book"
:
" The libraries provide the Thread.stop method, but this method was deprecated long ago because it is inherently unsafe—its use can result in data corruption. Do not use Thread.stop"
Anyone can tell me why ?
Upvotes: 0
Views: 1359
Reputation: 533680
IMHO, It's only unsafe if you use it to stop another thread. You can use it to stop the current thread without the normal issues e.g. if you need to re-throw a checked exception.
The problem with stop(), is you have no idea where in the thread you are throwing the exception or error. The only time you would consider using it is to stop third party threads which are not behaving correctly. The problem is that such threads can catch and ignore the error this triggers. If you really have unsafe or unreliable code you need to run, I suggest you use a separate process which you can kill as required.
Upvotes: 3
Reputation: 200206
In a nutshell, stop
aborts the thread forcibly without giving it any chance to clean up. The most typical outcome is a mess.
Upvotes: 1
Reputation: 68715
From the javadoc:
Why is Thread.stop deprecated?
Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.
For more information, read this:
http://docs.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html
Upvotes: 5
Reputation: 182829
What if the thread you stop holds a critical lock? What if the thread has placed an object into an inconsistent state and hasn't had a chance to restore it yet? The correct way to stop a thread is with its cooperation, not by forcing it to stop from the outside.
Also, it simply doesn't make logical sense. All the threads in an application are supposed to be cooperating to achieve the same ends. If there's something that shouldn't be done, no thread should do it. There should be no reason to stop a thread -- it should only be coded to do something if that is something the application as whole needs done in the first place. If a thread needs to be stopped, it's only because the code it is running is broken -- doing things even if they should not be done. Just fix that code.
Upvotes: 8