java - 在 Java 中处理 ClosedByInterruptException

标签 java exception nio

有很多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 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(),因为 channel 已经设置,或者只是简单地维护,线程的中断状态。我怀疑指定此行为是为了避免迫使开发人员重新中断线程,这与捕获 InterruptedException 不同。

关于java - 在 Java 中处理 ClosedByInterruptException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58697421/

相关文章:

java - FileChannel 和 FileInputStream 中 read(ByteBuffer) 和 read(byte[]) 之间的区别

java - 如何以通用方式访问 Java 构造函数?

java - 创建了多少字符串对象(String.format())?

python - try catch 异常时忽略打印语句

c# - 在 C# 中访问用户设置会引发异常

java - 在阻塞 ServerSocketChannel 上使用选择器

Java流形成 map 问题

java - JSP usebean 中的异常

java - @ExceptionHandler 没有捕获 HttpMessageNotReadableException

java - 一旦到达流结尾,是否应该显式关闭连接?