我对 Java 中的非阻塞 IO 很陌生。我有一个问题 - 如果在我们完成从 channel 的读取之后、但在从选择器中删除该 channel 的选择键之前来自服务器的新数据包到达,选择器是否会丢失非阻塞 channel 的准备状态?示例代码如下:
Selector selector;
// ......
while (true) {
selector.select();
Set<SelectionKey> set = selector.selectedKeys();
Iterator<SelectionKey> iterator = set.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(GOOD_ENOUGH_CAPACITY);
while (channel.read(byteBuffer) > 0) ;
// HERE ! What happen if server started to write new message here?
// Will this channel be selected on next selector.select() ?
iterator.remove();
}
}
最佳答案
是的,将选择 key 。您必须使用方法
key.cancel();
从选择器中删除键
关于java - NIO - channel 的就绪状态会丢失吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10261515/