Search code examples
javasocketsniosocketchannel

Java nio SelectionKey.register and interestops


I have been working on Java NIO communications and reading various writeups regarding this. The document says that I could "or" ops that I am interested in. However, I haven't seen a single example of

channel.register(selector,SelectionKey.OP_ACCEPT|SelectionKey.OP_READ|Selection.OP_WRITE)

Is this a bad idea?


Solution

  • Yep. It's wrong.

    1. The only thing that can deliver you an OP_ACCEPT is a ServerSocketChannel.
    2. The only thing that can deliver you an OP_READ or OP_WRITE is a SocketChannel or a DatagramSocketChannel.
    3. So there is no way a single channel can deliver you all three of those events. So there is no sense in registering for them all.
    4. OP_WRITE is almost always ready. It rarely if ever makes sense to register for OP_READ and OP_WRITE at the same time.

    The validOps() method tells you which operations are valid for a given channel, not that you should need to know at runtime.