Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: canonical thread stop Date: Thu, 24 Jul 2014 09:00:33 -0400 Organization: A noiseless patient Spider Lines: 33 Message-ID: References: <7cfe4089-8acd-4523-8ff7-3bad175571c3@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Thu, 24 Jul 2014 13:00:38 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="bd4e1cba8d8592bec5d5ed9e4537fbfd"; logging-data="20055"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/aSplVpr0nhtM7I0egxsUc" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Thunderbird/24.6.0 In-Reply-To: <7cfe4089-8acd-4523-8ff7-3bad175571c3@googlegroups.com> Cancel-Lock: sha1:sOeIqgkalyg8WHtW4M2prsZIn2g= Xref: csiph.com comp.lang.java.programmer:29270 On 7/24/2014 2:09 AM, mike75214@usa.com wrote: > Is there a canonical way to stop a thread in Java? (i.e. a method provided by Oracle) System.exit(status); // tee-hee That's only partly in jest. If you stop (or suspend) a thread "from the outside" without its cooperation, you have absolutely no idea what its state was. For example, it might have just stored the X position of something and have been about to store the Y position when the rug was ripped from beneath its feet; any other thread that subsequently uses the combined (X,Y) will get a completely bogus location -- the X from a moment ago and the Y from last week. The only safe way to stop or suspend a thread is with the thread's cooperation. It needs to get to a "safe" state, it needs to "put its affairs in order" before going to sleep or to the grave. And since what constitutes "safe" and "in order" is application-dependent, there's no one-size-fits-all pre-canned solution. Here's an analogy: You're driving down the highway when you hear a siren and see flashing blue lights in your rear-view mirror. So you pull over to the side of the road, slow down, stop, and await your fate. That's the right way to stop a thread: Signal it to stop and wait for it to do so safely. If instead the cop had zapped you with a phaser set on "stun," you'd find yourself hurtling down the road at high speed, paralyzed and unable to operate the controls, a menace to yourself and to others. That's the wrong way to stop a thread: Just halt it willy- nilly and pray there won't be too much "collateral damage." -- esosman@comcast-dot-net.invalid