I am working with Java selectors in NIO. I am registering my selection key/ interest key with the particular channels and selectors. Now, my requirement is to have two or more interest sets for a particular selector.
What I did is make two selectionkeys with different selection options as follows:
try {
Selector selector = Selector.open();
ServerSocketChannel channel = ServerSocketChannel.open();
//FileChannel channel = new FileInputStream("").getChannel();
channel.configureBlocking(false);
SelectionKey key1 = channel.register(selector, SelectionKey.OP_READ);
SelectionKey key2 = channel.register(selector, SelectionKey.OP_WRITE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
My question is, is there any way i can avoid making two diffrent keys?
You can binary-or the keys together to create a single interest:
SelectionKey key = channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);