nio小记 - 轮询SelectionKey为什么要删除

 // 轮询访问selector
        while (true) {
            // 当注册的事件到达时,方法返回;否则,该方法会一直阻塞
            // 多路复用  Reactor模型
            this.selector.select();
            // 无论是否有读写事件发生,selector每隔1s被唤醒一次  
             //this.selector.select(1000);
             //this.selector.selectNow();
            // 获得selector中选中的项的迭代器,选中的项为注册的事件
            Iterator<?> iteratorKey = this.selector.selectedKeys().iterator();
            while (iteratorKey.hasNext()) {
                SelectionKey selectionKey = (SelectionKey) iteratorKey.next();
                // 删除已选的key,以防重复处理
                iteratorKey.remove();
                
                new Thread(new Runnable() {
                    
                    @Override
                    public void run() {
                        // 处理请求
                        try {
                            handler(selectionKey);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        
                    }
                });
                
            }
        }
  • Selector.select()取出事件集中的全部事件,如果不删除,在下次轮询的时候,调用Selector.select()会取出旧的事件集,导致重复处理
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容