gpt4 book ai didi

java - 为什么在 Java NIO Selector 中使用 iterator.remove() 迭代 SelectionKey

转载 作者:行者123 更新时间:2023-12-02 03:49:08 24 4
gpt4 key购买 nike

以下代码摘自 HBase RpcServer.java。我不明白每次循环时都删除SelectionKey。这里面有什么原因吗?是优化吗?

      try {
selector.select();

Iterator<SelectionKey> it = selector.selectedKeys().iterator();

while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (key.isValid()) {
if (key.isReadable()) {
doRead(key);
}
}
}

} catch (IOException e) {
LOG.warn("Run into IOExpection in " + name, e);
}

最佳答案

selectedKeys 的结果包含当前可用于其所选操作(例如READWRITE)的 channel 的键。如果您不删除该键,它将保留在集合中,并且下一次调用 select()(和系列)仍将包含它,即使关联的 channel 尚未准备好选定的操作。

来自 Selector 的文档:

A selectable channel's registration with a selector is represented by a SelectionKey object. A selector maintains three sets of selection keys:

  • The key set contains the keys representing the current channel registrations of this selector. This set is returned by the keys method.
  • The selected-key set is the set of keys such that each key's channel was detected to be ready for at least one of the operations identified in the key's interest set during a prior selection operation. This set is returned by the selectedKeys method. The selected-key set is always a subset of the key set.

[..]

Keys are added to the selected-key set by selection operations. A key may be removed directly from the selected-key set by invoking the set's remove method or by invoking the remove method of an iterator obtained from the set. Keys are never removed from the selected-key set in any other way; they are not, in particular, removed as a side effect of selection operations. Keys may not be added directly to the selected-key set.

(强调我的)

关于java - 为什么在 Java NIO Selector 中使用 iterator.remove() 迭代 SelectionKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36041054/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com