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

This is a pretty straightforward question, but I found it necessary to unregister a selector that does not see 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 can I call something like this later in the program

 client.deregister(mySelector); 

And that the selector will no longer capture data keys for this socket channel. This would make life a lot easier for me, given my server / client design.

+8
java select nonblocking sockets socketchannel
source share
2 answers

Call cancel() on the select key:

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

or

 ... SelectionKey key = client.keyFor(mySelector); key.cancel(); 
+17
source share

In addition to @Nikolai answer. Running client.close() also unregisters the channel.

The key is added to its canceled selection key when it is canceled by closing its channel or by calling its cancellation method.

From https://docs.oracle.com/javase/7/docs/api/java/nio/channels/Selector.html

+1
source share

All Articles