简体   繁体   English

SeletionKey.cancel()和iterator.remove()的区别-Java

[英]Difference of SeletionKey.cancel() and iterator.remove() - java

What is the difference of key.cancel() and iterator.remove()? key.cancel()和iterator.remove()有什么区别? Removing the key from iterator isn't removing the key from selector too? 从迭代器中删除密钥也不会从选择器中删除密钥吗?

Suppose that: 假设:

...
SelectionKey key = (SelectionKey) iterator.next();
..
Iterator<SelectionKey> iterator  = selectedKeys.iterator();
...

Javadoc for SelectionKey says following.. SelectionKey的Javadoc表示如下。

A selection key is created each time a channel is registered with a selector. 每次在选择器中注册频道时,都会创建一个选择键。 A key remains valid until it is cancelled by invoking its cancel method, by closing its channel, or by closing its selector. 密钥一直有效,直到通过调用其cancel方法,关闭其通道或关闭其选择器将其取消。 Cancelling a key does not immediately remove it from its selector ; 取消键不会立即将其从选择器中删除 ; it is instead added to the selector's cancelled-key set for removal during the next selection operation. 而是将其添加到选择器的“取消键”集中,以便在下一次选择操作期间将其删除。

iterator.remove, remove it from the list. iterator.remove,将其从列表中删除。

When you call remove() on an Iterator , it just removes the object the Iterator is currently on from the list. 当您在Iterator上调用remove()时,它只会从列表中删除Iterator当前所在的对象。 It doesn't call any methods on the object, it doesn't affect it in any way -- it just takes it out of the list. 它不会在对象上调用任何方法,不会以任何方式影响它-只是将其从列表中删除。

When you call cancel() on a SelectionKey , it happens to do the same thing, but that's because cancel() requests that the list remove the object. 当您在SelectionKey上调用cancel()时,它恰好会做同样的事情,但这是因为cancel()请求列表删除该对象。 In addition, it's not guaranteed to happen instantly, whereas using remove() immediately removes the item from the list. 另外,它不能保证立即发生,而使用remove()立即从列表中删除该项目。 cancel() just makes it useless and, when it gets a chance, removes it from the list. cancel()只会使它无用,并且有机会将其从列表中删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM