javaexecutorserviceinterrupted-exception

Swallow InterruptedException in ExecutorService or not?


There is an article by IBM. https://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-#2.1

This says never swallow interruptedException. The same thing is there on sonar.

"InterruptedException" should not be ignored.

But there is a question on StackOverflow regarding interruptedException inside Executorservice, which suggests, we should not set the interrupt again. InterruptedException inside ExecutorService

Is the IBM article is quite old, and does not take the modern Java Concurrent package into account? How should we handle interruptedException in ExecutorService?


Solution

  • You should make a decision in all places you have trapped InterruptedException as it depends on the situation and importance for your code.

    A sensible response is for your task is to take heed of the interrupt, to allow a graceful cancellation or shutdown of the current thread or Runnable within executor. There won't much point resetting Thread.currentThread().interrupt() in your outermost part of a Runnable (as thread will exit just afterwards, or Executor is managing that interrupt).

    However if you are trapping that exception several layers of call stack below the task control then resetting Thread.currentThread().interrupt() may help the higher levels of your task see and bail out gracefully - but only if they are checking Thread.currentThread().isInterrupted() at each stage or your code passes on the InterruptedException or an application specific exception.