Java NIO Selector

In Java NIO the selector is a multiplexor of selectable channels, which is used as a special type of channel that can be put into non-blocking mode. It can examine one or more NIO Channel's and determines which channel is ready for communication i.e. reading or writing.


What is the use of Selector

The selector is used for handling the multiple channels using a single thread. Therefore it need less threads to handle the channels. Switching between the threads is expensive for operating system. Therefore, for improving the system efficiency it is use.

Let's see the illustration of a thread using Selector to handle 3 Channel's:

Let's see the simple illustration of the Gather principle:

Java Nio tutorial13

Creating a Selector

We can create a selector by calling Selector.open() method, as given below:


Opening a server socket channel

Let's see the example for opening a server socket channel:


Selection of Channels using a Selector

On registering one or more channels with a selector we can call one of a select() methods. This method return a channel which is ready for the events we want to perform i.e. connect, read, write or accept.

The various select() methods available for selection of channel are:

  • int select(): The integer value return by the select() method inform about how many channels are ready for the communication.
  • int select(long TS): This method is same as select() except it blocks the output for a maximum of TS(in millisecond) time period.
  • int selectNow(): It doesn't block the output and returns immediately with any channel which are ready.

selectedKeys()

Once we have called any one of the select() methods and it will return a value as indicated that one or more channels are ready, then we can access the ready channels by using the ?selected key set?, by calling a selectors selectedkeys() method as given below:

We can iterate the selected key set for accessing the ready channels as given below:

The above loop iterates a key in the selected key set for determining the operation performed using a selected channel.

The complete select loop block diagram is shown below:

Java Nio tutorial14

Basic Selector Example

Main Program:

Client Program:

Output:

The Main Program Output is:

The Client Program Output is:





Latest Courses