Search code examples
javasocketsselectnonblockingsocketchannel

Is there a way to de-register a selector on a socket channel


This is a pretty straight forward question, but I have found a need to unregister a selector overlooking my socket channel for java.

SocketChannel client = myServer.accept(); //forks off another client socket
client.configureBlocking(false);//this channel takes in multiple request
client.register(mySelector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);//changed from r to rw

Where I can later in the program call something like

client.deregister(mySelector);

And that the selector will no longer catch data keys for that socket channel. This would make life much easier for me given my server/client design.


Solution

  • Call cancel() on the selection key:

    SelectionKey key = client.register(mySelector,
        SelectionKey.OP_READ | SelectionKey.OP_WRITE);
    ...
    key.cancel();
    

    or

    ...
    SelectionKey key = client.keyFor(mySelector);
    key.cancel();