Java NIO Selector
Selector is a mutiplexer.
Basically aggregate multiple channel into one bundle so we don’t have to switch between different thread. By doing so, we can use one thread to handle multiple channel.
create
Seems like there is only one way to create selector.
1 |
|
register channel
Each channel must register to selector is order to subscribe to coming event.
1 |
|
The second parameter is interest operations
, which is a list of operations that this channel is interested in.
SelectionKey.OP_CONNECT
As a client, waiting for server to accept my connection requestSelectionKey.OP_ACCEPT
As a server, waiting for client connection requestSelectionKey.OP_READ
Waiting for data readingSelectionKey.OP_WRITE
Waiting for data writing
These interest operations
are just integer number, so they can be combined using bitwise operator like A|B
, to indicate multiple interests for single channel.
listen
Now that we have channel registered, let us waiting for incoming request.
1 |
|
get inbound
Then we need to know which exact channel get ready.
1 |
|
close channel
When want to close channel connection, we may use cancel
or close
This will deregister itself from channel as well.
1 |
|
close selector
Shutdown entire selector by closing it.
1 |
|