As long-time developer, I have recently (finally) had to pick up Java as a language and was curious about the conventional way I see Java NIO selectors are iterated.
As pointed out on this previous question and also this duplicate one, calling select()
on a selector will only add to the selected keys set, and keys must be explicitly removed after processing to indicate they have been serviced.
Most examples look something like:
while(true) {
selector.select();
Iterator iter = selector.selectedKeys().iterator();
while(iter.hasNext()) {
Selection key = iter.next();
process(key);
iter.remove();
}
}
My question is, in the simple implementation above, where all selected keys are processed and removed, why are the keys removed on each iteration instead of all at once?
For example:
while(true) {
selector.select();
for(Selection key : selector.selectedKeys()) {
process(key);
}
selector.selectedKeys().clear();
}
Apart from exception handling on the process step, are the two code samples equivalent? Or is there something fundamentally different about one-by-one iteration and removal vs for-loop iteration and clearing? Or is this just a matter of style and convention?