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
Propagate the InterruptedException
- Declare your method to throw the checked InterruptedException
so that your caller has to deal with it.
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.
Uninterruptibles
. Uninterruptibles
take over the boilerplate code like in the Noncancelable Task example in JCIP ยง 7.1.3.