Why is Thread.stop()
deprecated in Java? On their website, I see the following:
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.
I don't understand what they mean by "monitors". Regardless, my question is if Thread.stop()
should not be called then how should a Java thread be stopped?
When your thread handles interrupts correctly, it should be possible to instantly terminate it with use of
ExecutorService
interface. According to Oracle documentation,ExecutorService.shutdownNow()
method, attempts to stop all actively executing tasks without waiting for their termination. There are however no guarantees beyond best-effort attempts to stop them. Here is some sample code:Without termination each thread should print message to console 10000000 times.
executor.shutdownNow()
method instantly stops all three threads.You asked:
The Answer: In Java there's no clean, quick or reliable way to stop a thread.
Instead, Threads rely on a cooperative mechanism called Interruption. This means that Threads could only signal other threads to stop, not force them to stop.
Source: http://10kloc.wordpress.com/2013/03/03/java-multithreading-steeplechase-stopping-threads/
From https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html:
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.
Here exampleThread.join() will wait until exampleThread is done executing before moving to the next statement. However, the onus of making sure that the thread does finish execution is on the programmer. In essence there is no way to stop a thread but if you design it right you should not need to stop the thread.