Figure 4-3. Cancellation
How to make cancellation work correctly, in bounded time, and without corrupting any data is a
different story. That part is highly complex and handled in Chapter 9. Moreover, thread.stop()
has been deprecated in JDK 1.2. We'll discuss this in Don't Call stop(). Although deprecated,
stop() will continue to be supported in Java for an unspecified amount of time. (It may never
There is another technique that is more suitable for cancellation in Java. This is to interrupt the
target thread and cause it to throw an InterruptedException. We can catch that exception
The stop() method is implemented by causing the target thread to throw an unchecked
exception, ThreadDeath. That exception then percolates up to the run() method, where it
causes the thread to exit. The original implementation of Java was not intended to expose
ThreadDeath, but through some odd circumstances, it got out. You should consider it to be part
of the implementation though, and not use it yourself. Yes, you could throw it yourself. You could
even catch it yourself, but there are better ways of accomplishing whatever task you had in mind.
Don't do that.
Garbage Collecting Threads
When do threads and thread objects get garbage collected? If you drop the last pointer to a thread,
will it stop running and be garbage collected? No. When a thread is started, the thread object is
entered into a thread group (see Thread Groups) and will remain there until it exits. The top-
level thread group is one of the root GC nodes, so it never disappears.
As soon as a thread exits, its stack will be freed (this is an implementation detail), and some time
after it exits and you drop the last pointer to the thread object, that thread object will be garbage
collected. In other words, everything works the way you think it should and there's nothing to
In POSIX, a zombie thread is a dead thread whose memory has not yet been reclaimed.
Reclamation occurs when that thread is joined. Java does not have this issue, so it is devoid of
zombies; however, the underlying libraries may well use them to support Java. Nonetheless,
imagining zombies in Figure 4-4 can help clarify the concept.
Search WWH :