Handling InterruptedException in Java

前端 未结 7 727
长发绾君心
长发绾君心 2020-11-22 10:45

What is the difference between the following ways of handling InterruptedException? What is the best way to do it?

try{
 //...
} catch(Interrupt         


        
7条回答
  •  长发绾君心
    2020-11-22 11:41

    As it happens I was just reading about this this morning on my way to work in Java Concurrency In Practice by Brian Goetz. Basically he says you should do one of three things

    1. Propagate the InterruptedException - Declare your method to throw the checked InterruptedException so that your caller has to deal with it.

    2. Restore the Interrupt - Sometimes you cannot throw InterruptedException. In these cases you should catch the InterruptedException and restore the interrupt status by calling the interrupt() method on the currentThread so the code higher up the call stack can see that an interrupt was issued, and quickly return from the method. Note: this is only applicable when your method has "try" or "best effort" semantics, i. e. nothing critical would happen if the method doesn't accomplish its goal. For example, log() or sendMetric() may be such method, or boolean tryTransferMoney(), but not void transferMoney(). See here for more details.

    3. Ignore the interruption within method, but restore the status upon exit - e. g. via Guava's Uninterruptibles. Uninterruptibles take over the boilerplate code like in the Noncancelable Task example in JCIP § 7.1.3.

提交回复
热议问题