I want to gracefully shutdown the threads. I seen many codes on internet and have query here.
I think there are two approaches to shutdown.
- use boolean flag. Once flag chnages we can break the code there in run method.
- use of interrupt method.
My question why it is avoided to use boolean flag to gracefully shutdown the threads, When I ran sample program it went well.
There is nothing wrong with
booleanflag, however:you need to remember about synchronization/visibility (at least put
volatileon the flag)why adding an extra flag when one is already implemented (
interrupted)?Other libraries/containers might try to interrupt your thread (after all, they don’t know about your flag!) so you still need to support
InterruptedExceptionand/orisInterrupted()flaginterrupting a thread can also interrupt I/O calls and
Thread.sleep(). Your custom flag can’t