Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 474
Dr.Knowitall Avatar asked Dec 13 '12 19:12

Dr.Knowitall


People also ask

What is a selector thread?

A selector provides a mechanism for monitoring one or more NIO channels and recognizing when one or more become available for data transfer. This way, a single thread can be used for managing multiple channels, and thus multiple network connections.

What is a socket channel?

A selectable channel for stream-oriented connecting sockets. A socket channel is created by invoking one of the open methods of this class. It is not possible to create a channel for an arbitrary, pre-existing socket. A newly-created socket channel is open but not yet connected.


2 Answers

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();
like image 67
Nikolai Fetissov Avatar answered Sep 30 '22 17:09

Nikolai Fetissov


In addition to @Nikolai 's answer. Doing client.close() will also deregister the channel.

A key is added to its selector's cancelled-key set when it is cancelled, whether by closing its channel or by invoking its cancel method.

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

like image 31
gokul_uf Avatar answered Sep 30 '22 18:09

gokul_uf