Re: When the stop() in Thread class changed to final method?
RC wrote On 02/01/07 16:58,:
Daniel Pitts wrote:
On Feb 1, 7:27 am, RC <raymond.c...@nospam.noaa.gov> wrote:
If you go to this link
http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDepreca...
That document you linked to is suggesting that you override the stop
method in Applet, not Thread.
Then, do you know how I can stop a thread since Thread.stop()
has deprecated. Can I just make a thread = null?
The reason Thread.stop() is deprecated isn't because of
some deficiency in the method, but because the entire idea
of stopping a Thread dead in its tracks is unsafe. Perhaps
you were taught as a child that putting your hand on a hot
stove is deprecated; it does not follow that putting your
fanny there would be an improvement.
Here's an analogy that may help you understand why it
is a bad idea to stop a Thread without its cooperation. As
a wealthy person, you no doubt have lots of investments and
a personal banker to take care of them. The banker is busy
on your behalf, moving money from one account to another all
day long, trying to make your Midas-like wealth accumulate
as fast as possible. Your banker, if you haven't already
guessed, is named Mr. Thread.
One day, in a fit of rich man's pique, you decide you
no longer need the banker's services, so you say to Thread
"Stop right where you are. You're fired. Out of my sight,
and stay out!"
Unfortunately for you, Thread had just that moment taken
a bazillion dollars out of one of your accounts and was about
to deposit it in another. But you told him to stop, so that's
what he did -- and he left your sight, as instructed, still
with your bazillion dollars in his hands. Welcome to the
poorhouse, Mister Rich Man!
Do you get the point now? If you stop a Thread at some
random point in its execution, you don't know what it was
doing at the moment it ceased to execute. It might have been
somewhere in the middle of a sequence of steps that should
either be completed in their entirety or not begun at all;
the half-completed states are not desirable.
So, how do you stop a Thread in a controlled fashion?
One way is to have the Thread's Runnable check a "please shut
down now" flag every so often, at a point where things are
stable and there's no half-completed sequence of steps in
progress. Instead of firing your banker on the instant, you
say at the beginning of your relationship, "Thread, I want
you to call my office precisely at nine o'clock every morning,
before starting work, in case I have special instructions."
And when the day comes, your instructions are "Clear out your
desk, Thread." That way, he's fired when he's not in the
middle of something you'd prefer weren't interrupted.
--
Eric.Sosman@sun.com