tempus-fugit

Java micro-library for writing & testing concurrent code

Handling Interrupt Exceptions

How should you handle InterruptedExceptions?

1
2
3
4
5
try {
    Thread.sleep(100);
} catch (InterruptedException e) {
    // what to do?
}

You could rethrow if it’s appropriate but often its not. If that’s the case, you should set the interrupt status flag associated with the current thread. For example,

1
2
3
4
5
try {
    Thread.sleep(100);
} catch (InterruptedException e) {
    Thread.currentThread().interrupt(); // reset the interrupt status
}

Typically, if a Java method throws InterruptedException, it will have reset the interrupt status before doing so. In the example above, you’re just restoring it and preserving a flag to indicate the thread had once been interrupted.

The reason for preserving this status flag is in case code other than your own depends on it. For example, a framework (which you may not appreciate is actually being used), may be doing something like the following to (correctly) support interruption.

1
2
3
while (!Thread.currentThread().isInterrupted()) {
    process();
}

You should generally never just catch the exception and ignore it; it may cripple code depending on the status flag for correct behaviour. In the same way, it’s rarely a good idea to catch and exception and just log it, especially in the case of InterruptedException.

Over to you...