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.
The right way is to use a join. Instead of prematurely stopping the execution of a thread, join will wait for the thread to finish execution before moving to the next statement.
Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected. A thread will also move to the dead state automatically when it reaches the end of its method.
stop is being 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.)
Read these articles, they explain it:
"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
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With