0

Following code cut from HBase RpcServer.java. I can't understand that remove SelectionKey in each time of loop.Are there some reasons in here?Is it a optimizing?

      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);
    }
Zephyr Guo
  • 1,083
  • 1
  • 8
  • 14
  • I don't know hbase but since there is `selector.select();` at the top I'd guess it's meant to somewhat reset the selection, i.e. remove elements that are being processed. – Thomas Mar 16 '16 at 16:10
  • @Thomas The `selector` is part of the Java NIO API, and has nothing to do with HBase itself. – Mark Rotteveel Mar 16 '16 at 16:21

1 Answers1

3

The result of selectedKeys contains the keys to channels that are currently available for their selected operations (eg READ, WRITE). If you don't remove the key, it will remain in the set, and a next call to select() (and family) will still include it, even though the associated channel is not ready for the selected operation.

From the documentation of 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.

(emphasis mine)

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197