在 Java 中处理 ClosedByInterruptException

Handling ClosedByInterruptException in Java

有很多detailed advice about handling InterruptedException properly. Do any of the same principles apply to handling ClosedChannelException from NIO calls, which can be a ClosedByInterruptException?特别是抓CBIE时,应该叫Thread.currentThread().interrupt()吗?

这是 ClosedByInterruptException 的文档所说的(强调 我的):

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.

此外,ClosedByInterruptException class 及其超级 class、AsynchronousCloseException 与实施 InterruptibleChannel 的渠道相关联。该接口的文档说(强调我的):

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.

换句话说,您不需要在捕获到 ClosedByInterruptException 后调用 Thread.currentThread().interrupt(),因为通道已经设置或只是维护了线程的中断状态。我怀疑指定此行为是为了避免迫使开发人员不得不重新中断线程,这与捕获 InterruptedException.

时不同。