2

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.

  1. use boolean flag. Once flag chnages we can break the code there in run method.
  2. 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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
user900721
  • 1,417
  • 4
  • 17
  • 29

1 Answers1

5

There is nothing wrong with boolean flag, however:

  • you need to remember about synchronization/visibility (at least put volatile on 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 InterruptedException and/or isInterrupted() flag

  • interrupting a thread can also interrupt I/O calls and Thread.sleep(). Your custom flag can't

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674