Alternate to Thread.stop() in Java 8? Alternate to Thread.stop() in Java 8? multithreading multithreading

Alternate to Thread.stop() in Java 8?


Read these articles, they explain it:

  1. "Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?"http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

  2. Joshua Bloch: "Effective Java (2nd Edition)", Item 66: Synchronize access to shared mutable data

Joshua Bloch explains how to stop a thread and says this:

Consider the task of stopping one thread from another. 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. A recommended way to stop one thread from another is to have the first thread poll a boolean field that is initially false but can be set to true by the second thread to indicate that the first thread is to stop itself.

When using this technique you should handle also synchronization of the boolean field. I don't want to copy too much stuff from Joshua Bloch's book, but you will find everything there and in the official Oracle Java documentation mentioned above.


If you really need to stop a Thread the hard way you may consider that the method Thread.stop() (without providing an arbitrary Throwable) still works with Java 8. It will generate a ThreadDeath on the stopped thread which can be handled like any other Error, despite its unusual name. The only difference is that no stack trace will be printed if ThreadDeath is not caught.


But beware that this method is deprecated for most of the same reasons than the other stop method. It might become unspported in one of the next releases of Java. So it’s still time to think about a plan B…


The right way to stop a thread is to call interrupt on it.