agrona
agrona copied to clipboard
How is NioSelectedKeySet intended to be used?
I am looking for help on how to use NioSelectedKeySet and its intended usage. Should I copy the TransportPoller and modify? What if I want to use multiple selectors? with static Fields in the transport poller what would happen if i instantiate multiple transport pollers?
I have tried the following which is to extend the TransportPoller provided and create methods to register channels to selector and to perform select operations. Is this the correct/intended usage?
public class SelectorOptimizer extends TransportPoller {
private final String SELECT_MODE;
private final int SELECT_TIMEOUT;
public SelectorOptimizer(String selectMode, int selectTimeout){
super();
this.SELECT_MODE = selectMode;
this.SELECT_TIMEOUT = selectTimeout;
}
public void registerChannel(UDPChannel channel) throws ClosedChannelException {
channel.getCHANNEL().register(this.selector, SelectionKey.OP_READ, channel);
}
public SelectionKey[] performSelection() throws IOException {
this.selectedKeySet.clear();
int readyKeys;
if (SELECT_MODE.equals("BLOCK")) {
readyKeys = this.selector.select();
} else if (SELECT_MODE.equals("TIMEOUT")) {
if (SELECT_TIMEOUT != 0) {
readyKeys = this.selector.select(SELECT_TIMEOUT);
} else {
readyKeys = this.selector.select(5000);
}
} else {
readyKeys = this.selector.selectNow();
}
return selectedKeySet.keys();
}
}
NioSelectedKeySet is only intended to be using with TransportPoller as a workaround to avoid the memory allocation that occurs in Selector#selectedKeys. If you are running JDK 11 or later, then you should use Selector#select(Consumer<SelectionKey> action) instead of NioSelectedKeySet.