Threads are an often under-observed subject when developing in Java, primarily because errors of this kind present themselves very subtlety, and its not after exploring what are more obvious causes that threads come up on the troubleshooting list. In this continuing series addressing concurrency issues in Enterprise Java, Peter Veentjer takes on the subject of stopping threads, describing both their visibility and reordering problems, including a solution to these issues.
Stopping a Thread is complicated. In the beginning the Thread.stop() method was added for this purpose, but is has been deprecated for a long time. The reason is when some thread calls stop() on a victim thread, a ThreadDeath error is thrown inside the victim thread. And while this error propagates up the stacktrace, all locks the victim thread owns, are released. This means that the victim-thread could leave objects (on which it held locks) in an inconsistent state. So stopping a thread should be a cooperative mechanism between threads: the victim thread and the initiating thread both need to agree upon a protocol being used. Luckily I don't see the usage of Thread.stop() (or even worse, the Thread.destroy()) often, but the idiom displayed in the example below, is something I do see regularly. Although the exception handling is sometimes forgotten. This Task is executed by some thread, and when a different thread wants to stop this Task, it calls the stop method on the Task and the stop variable is set to true. As soon as the victim thread starts the next iteration of the loop, it reads the stop variable, ends the loop and returns from the run method (returning from the run method eventually terminates the victim thread).
Read Peter Veentjer post on stopping threads : http://blog.xebia.com/2008/02/12/ejcp-9-stopping-threads/