Java NIO SelectorIn 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 SelectorThe 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: Creating a SelectorWe can create a selector by calling Selector.open() method, as given below: Opening a server socket channelLet's see the example for opening a server socket channel: Selection of Channels using a SelectorOn 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:
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: Basic Selector ExampleMain Program: Client Program: Output: The Main Program Output is: The Client Program Output is: Next TopicJava NIO SocketChannel |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India