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)