假设你在评论中提到,在一定时间之后将中断频道,你需要处理两个案件,每个案件都有自己的检查例外:
- Case 1 : Another thread invoked
close()
on the channel while your thread is blocked on an I/O operation. Your call to write
will abort with an AsynchronousCloseException
.
- Case 2 : Another thread called
interrupt()
on your thread while it s blocking on an I/O operation. Your call to write()
will abort with a ClosedByInterruptException
.
请更新你的法典,处理这些例外情况:
this.outstream = Channels.newChannel(outstream);
try {
outstream.write(message);
}
catch(AsynchronousCloseException e) {
System.out.println("Another thread closed the stream while this one was blocking on I/O!");
}
catch(ClosedByInterruptException e) {
System.out.println("This thread has been interrupted while blocking on I/O!");
}
Take care to notice that the contract of InterruptibleChannel
specifies that these exceptions will only be thrown if the current thread is blocked in an I/O operation. If your thread isn t blocking, then neither of these exceptions will be thrown. In that case, it s likely that if another thread closed the channel you d get a different IOException for trying to write to a closed channel, and if you re not paying attention to the current thread s interrupted status, it will keep writing. However, since behavior for that case is not specified by the interface, it s up to the implementor to decide what to do.