Search code examples
javaselectornio

NIO - How to make SelectionKey to be interested in NO opts


How do you make java.nio.channels.SelectionKey to be interested in NO opts?

SelectionKey#cancel() has possibility but is not so good, because it makes the key useless.

SelectionKey has interestOps constants; OP_ACCEPT, OP_CONNECT, OP_READ and OP_WRITE, but not OP_NOTHING. Then is it legal operation to call SelectionKey#interestOpts(**0**)?

Here is an example.

for(;;) {
    selector.select();
    for (Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            it.hasNext();) {
        SelectionKey key = it.next(); it.remove();
        key.interestOps(0);     // interested in no opts.

        // another thread handles socket...
        worker.handle();
    }
    updateKeys();     // if the worker completes handling,
                      // other interestOpts are set...
}

This code works for me so far, but I doubt it is legal to call SelectionKey#interestOpts(0). Or could you tell me your best practice?


Solution

  • I doubt it is legal to call SelectionKey#interestOpts(0)

    Why? Where does it say that in the Javadoc?

    It's perfectly legal. You've answered your own question.