7

Why is Thread.stop() so dangerous?

Why is it advisable to use Thread.interrupted() instead?

I know stop is deprecated. What other thing makes it unsafe?

Is there any place where I can use stop method? If so give me an example.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 11
    Did you read http://download.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html as linked from the Thread.stop javadocs? – Jon Skeet Mar 07 '11 at 11:16
  • 1
    +1, my hand did the upvote whilst my brain was contemplating none :) – adarshr Mar 07 '11 at 11:20

1 Answers1

10

Why is Thread.stop() so dangerous?

The problems are described in detail here: http://download.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

Why is it advisable to use Thread.interrupted() instead?

Because Thread.interrupt() lets the target thread of the interrupt respond when it reaches a point when it knows it is safe to do so.

I know stop is deprecated. What other thing makes it unsafe?

See link above.

Is there any place where I can use stop method? If so give me an example.

In theory, if you knew that the thread you were stopping:

  • didn't ever update data structures shared with other threads,
  • didn't use wait/notify or higher level synchronization classes, or classes that depended on them,
  • and possibly a few other things.

For example, I think it would be safe to stop() this thread:

new Thread(new Runnable(){
    public void run(){for (long l = 0; l > 0; l++){}}).start();

However, in most cases it is too difficult to do the analysis to figure out if calling stop() will really be safe. For instance, you have to analyse every possible bit of code (including core and 3rd-party libraries) that the thread uses. So that makes it unsafe by default.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 6
    +1: The problem with using stop() is that it only works safely with well behaved, well understood, simple threads, however if its well behaved you shouldn't need to use stop(). – Peter Lawrey Mar 07 '11 at 12:28