java - NIO - channel 的就绪状态会丢失吗?

标签 java nio

我对 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/

相关文章:

java - 什么是最适合输入 Long 值的 SWT 小部件?

java - guava hashbimap 是可序列化的吗?

java - 如何模拟未作为参数传递的对象

使用 Files.move() 时出现 java.nio.file.AccessDeniedException

java - 停止监视目录的变化(清理)

java - PreparedStatement setnull 方法中 Types.INTEGER 和 Types.NULL 的区别

java - 按 ID 查找所有 View

java - 如何获取 Windows 负载值

java - nio缓冲区类中的limit()有什么用

Java NIO - 使用 SocketChannel 接收数据的问题