I am new to a non-blocking IO in Java. I have a question – will a readiness of a non-blocking channel be lost by the selector, if a new packet from a server will arrive after we completed reading from the channel, but before we removed a selection key for this channel from selector? Example code here:
Selector selector;
// ......
while (true) {
selector.select();
Set<SelectionKey> set = selector.selectedKeys();
Iterator<SelectionKey> iterator = set.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(GOOD_ENOUGH_CAPACITY);
while (channel.read(byteBuffer) > 0) ;
// HERE ! What happen if server started to write new message here?
// Will this channel be selected on next selector.select() ?
iterator.remove();
}
}
Yes, key will be selected. You must use method
to remove key from selector