成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

為什么要在java nio的`selector.selectedKeys()。iterator()`中刪除鍵?

瀏覽:140日期:2024-04-26 10:56:48
如何解決為什么要在java nio的`selector.selectedKeys()。iterator()`中刪除鍵??

由于選擇器從不執(zhí)行此操作,因此只會(huì)添加到集合中,因此,如果不這樣做,則下次選擇器返回時(shí),您將自己重新處理事件。

解決方法

我發(fā)現(xiàn)了一些java nio的示例代碼:

ServerSocketChannel server = ServerSocketChannel.open(); Selector selector = Selector.open(); server.socket().bind(new InetSocketAddress(8080)); server.configureBlocking(false); server.register(selector,SelectionKey.OP_ACCEPT); while(true) { selector.select(); Iterator iter = selector.selectedKeys().iterator(); while (iter.hasNext()) { SelectionKey key = (SelectionKey) iter.next(); iter.remove(); // Why remove it? process(key); } }

當(dāng)他獲得選定的鍵時(shí),他將循環(huán)中的鍵刪除。為什么我們應(yīng)該這樣做?

更新

感謝 EJPuser270349 提供的答案,我想我現(xiàn)在已經(jīng)明白了,讓我詳細(xì)解釋一下。

選擇器中有2個(gè)表:

登記表:當(dāng)我們呼叫時(shí)channel.register,其中會(huì)有一個(gè)新的項(xiàng)目(密鑰)。僅當(dāng)我們調(diào)用時(shí)key.cancel(),它將從此表中刪除。

準(zhǔn)備好選擇表:當(dāng)我們調(diào)用時(shí)selector.select(),選擇器將查找注冊(cè)表,找到可用的鍵,并將它們的引用復(fù)制到該選擇表中。選擇器不會(huì)清除此表中的項(xiàng)目(這意味著,即使我們selector.select()再次調(diào)用,它也不會(huì)清除現(xiàn)有項(xiàng)目)

這就是為什么iter.remove()當(dāng)我們從選擇表中獲得鍵時(shí)必須調(diào)用的原因。如果沒有,selector.selectedKeys()即使它尚未準(zhǔn)備好使用,我們也會(huì)一次又一次地獲得密鑰。

標(biāo)簽: java
相關(guān)文章: