有很多detailed advice about handling InterruptedException
适本地。任何相同的原则是否适用于处理ClosedChannelException
来自 NIO 调用,可以是 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
类及其父类(super class) AsynchronousCloseException
与实现 InterruptibleChannel
的 channel 关联。 。该接口(interface)的文档说(强调我的):
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 anAsynchronousCloseException
.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 aClosedByInterruptException
, 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()
,因为 channel 已经设置,或者只是简单地维护,线程的中断状态。我怀疑指定此行为是为了避免迫使开发人员重新中断线程,这与捕获 InterruptedException
不同。
关于java - 在 Java 中处理 ClosedByInterruptException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58697421/