2

There is a lot of detailed advice about handling InterruptedException properly. Do any of the same principles apply to handling ClosedChannelException from NIO calls, which can be a ClosedByInterruptException? In particular, when catching a CBIE, should Thread.currentThread().interrupt() be called?

user207421
  • 305,947
  • 44
  • 307
  • 483
John Dough
  • 400
  • 3
  • 9

1 Answers1

3

Here's what the documentation of ClosedByInterruptException says (emphasis mine):

Checked exception received by a thread when another thread interrupts it while it is blocked in an I/O operation upon a channel. Before this exception is thrown the channel will have been closed and the interrupt status of the previously-blocked thread will have been set.

Also, the ClosedByInterruptException class and its superclass, AsynchronousCloseException, are associated with channels which implement InterruptibleChannel. The documentation of that interface says (emphasis mine):

A channel that can be asynchronously closed and interrupted.

A channel that implements this interface is asynchronously closeable: If a thread is blocked in an I/O operation on an interruptible channel then another thread may invoke the channel's close method. This will cause the blocked thread to receive an AsynchronousCloseException.

A channel that implements this interface is also interruptible: If a thread is blocked in an I/O operation on an interruptible channel then another thread may invoke the blocked thread's interrupt method. This will cause the channel to be closed, the blocked thread to receive a ClosedByInterruptException, and the blocked thread's interrupt status to be set.

If a thread's interrupt status is already set and it invokes a blocking I/O operation upon a channel then the channel will be closed and the thread will immediately receive a ClosedByInterruptException; its interrupt status will remain set.

A channel supports asynchronous closing and interruption if, and only if, it implements this interface. This can be tested at runtime, if necessary, via the instanceof operator.

In other words, you do not need to call Thread.currentThread().interrupt() after catching a ClosedByInterruptException because the channel will have already set, or simply maintained, the interrupt status of the thread. I suspect this behavior is specified especially to avoid forcing developers having to re-interrupt the thread, unlike when catching an InterruptedException.

Slaw
  • 37,820
  • 8
  • 53
  • 80