我是Java中非阻塞IO的新手。我有一个问题 - 如果来自服务器的新数据包在我们完成从频道读取后到达,但在我们从选择器中删除了该频道的选择键之前,选择器是否会丢失非阻塞频道的准备就绪?示例代码:
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();
}
}
答案 0 :(得分:1)
是的,将选择密钥。你必须使用方法
key.cancel();
从选择器中删除密钥