Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 499
sksamuel Avatar asked Apr 17 '26 23:04

sksamuel


1 Answers

In the first version, you can share the shutdown flag (or a similar shutdown mechanism) with the calling code, allowing it to attempt a completely graceful shutdown just by setting the flag, without interrupting the thread - possibly falling back to interruption if the graceful shutdown fails.

I wouldn't suggest using thread interruption as your only shutdown mechanism.

(Equally, be careful with how you handle the shared flag, of course. You'll need to make it thread-safe; a volatile variable would probably be enough in simple cases.)

like image 118
Jon Skeet Avatar answered Apr 19 '26 15:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!