Search code examples
javamultithreadingrequest-cancelling

Java Threads: Shutdown flag vs Catching Exception


In threads when dealing with cancelation, you often you see code like this

while (!shutdown) {
  .. do something, if a blocking call, then it will throw the interrupted exception
  try { .. some more ... } 
  catch (InterruptedException e) { 
    shutdown = true; 
  }
}

What I want to know is, is this, or why is this, better than doing this

try {
  while (true) {
    .. do something, if a blocking call, then it will throw the interrupted exception
    if (Thread.interrupted()) throw new InterruptedException();
  }
} catch (InterruptedException e) {
  .. clean up, let thread end
}

The way I see it is that in the latter case you don't need to bother with the shutdown var at all.


Solution

  • You don't use exceptions as a way to exit from a condition (at least not typically, and it is a practice best to be avoided.) An exception is for ... cue drums ... announce exceptions, errors, situations and conditions that are typically or potentially bad.

    A shutdown is not (typically) an error condition, so at least from that philosophical/design point of view, I would prefer the first option using the shutdown flag variable.

    Also, the flag can be externalized as a read-only property (say, as a getter). Then components external to the thread can see whether the thread is still active (if they have logic that legitimately depends on that.)

    On a personal note, I dislike that Java uses InterruptedException as it is typically not an exception per say, but a signal, typically a normal and expected signal. Oh well.