简体   繁体   中英

Alternate to Thread.stop() in Java 8?

Is there any way to force a Thread to stop under Java 8 , now that Thread.stop has been removed? This includes forcing a thread waiting on a lock/synchronized/sleep/wait/infinite loop to stop.

This is intended as part of a watchdog for the application which can detect if it has deadlocked/frozen , force kill threads and then save the current state to avoid lost information - while there is a high chance of this information being corrupt due to forcing a thread to stop, it's better to have a copy of the possibly incorrect information than to lose it.

Attempting to save this information without stopping the locked up threads is impossible, as saving it will require acquiring locks.

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…

停止线程的正确方法是在其上调用interrupt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM