为什么要在java nio中的`selector.selectedKeys()。iterator()`中删除键? [英] Why the key should be removed in `selector.selectedKeys().iterator()` in java nio?

查看:452
本文介绍了为什么要在java nio中的`selector.selectedKeys()。iterator()`中删除键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一些java nio的示例代码:

I found some sample code of 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);  
     }
 }

当他获得所选择的密钥时,他会删除密钥在循环。我们为什么要这样做?

When he gets the selected keys, he remove the key in the loop. Why we should do this?

更新

感谢 EJP user270349 提供的答案,我想我现在明白了,让我详细解释一下。

Thanks to the answers provided by EJP and user270349, I think I understand it now, let me explain it in detail.

选择器中有2个表:


  1. 注册表:当我们调用<$ c时$ c> channel.register ,会有一个新项目(密钥)。只有当我们调用 key.cancel()时,它才会从此表中删除。

  1. registration table: when we call channel.register, there will be a new item(key) into it. Only if we call key.cancel(), it will be removed from this table.

ready对于选择表:当我们调用 selector.select()时,选择器将查找注册表,找到可用的键,将它们的引用复制到此选择中表。选择器不会清除此表的项目(也就是说,即使我们再次调用 selector.select(),它也不会清除现有项目)

ready for selection table: when we call selector.select(), the selector will look up the registration table, find the keys which are available, copy the references of them to this selection table. The items of this table won't be cleared by selector(that means, even if we call selector.select() again, it won't clear the existing items)

这就是为什么我们必须调用 iter.remove()当我们从选择表中获得密钥时。如果没有,我们将一次又一次地通过 selector.selectedKeys()获取密钥,即使它还没有准备好使用。

That's why we have to invoke iter.remove() when we got the key from selection table. If not, we will get the key again and again by selector.selectedKeys() even if it's not ready to use.

推荐答案

因为Selector永远不会这样做,所以它只会添加到集合中,所以如果你不这样做,你将在下次Selector返回时自己重新处理事件。

Because the Selector never does that, it only adds to the set, so if you don't do it you will reprocess the event yourself next time the Selector returns.

这篇关于为什么要在java nio中的`selector.selectedKeys()。iterator()`中删除键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆