In the below code, i have a while(true) loop. considering a situation where there is some code in the try block where the thread is supposed to perform some tasks which take
I recommend using Thread.interrupt()
(as mentioned by @Bohemian). It has a couple of advantages over using ad-hoc flags:
You don't need to create and use an application-specific API to do this. (And interrupts are guaranteed thread-safe ...)
Thread.interrupt()
will interrupt threads that are blocked in a wait()
or a join
, or possibly1 some blocking I/O calls.
However, it is not a magic bullet. If the thread you are trying to stop is executing regular code, it needs to periodically check its interrupted()
flag, or it won't no to stop. This leaves us in the same as boat as we are in with an ad-hoc flag mechanism. The thread has to cooperate, or it can't be (safely) stopped.
1 - This is a murky area. On the one hand, there is an InterruptedIOException
whose javadoc says "Signals that an I/O operation has been interrupted". On the other hand, the exception is not explicitly mentioned in the javadocs for the various java.io
stream classes.
It is true that some 3rd-party code may not deal with the interrupted
flag properly, and interrupts may get "eaten" as a result. But you can check for that if you have source code. And the situation is not a lot different to the 3rd-party code not paying attention to your ad-hoc flag mechanism.
I would NOT recommend using Thread.stop()
. It is fundamentally flakey. Some people claim that it works for them, but IMO they are either dealing with a special case that works ... or they are being lucky.