EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Java NIO Tutorial Java NIO Selector
Secondary Sidebar
Java NIO Tutorial
  • Java NIO Tutorial
    • Java NIO Channel
    • Java NIO
    • Java nio ByteBuffer
    • Java nio file AccessDeniedException
    • Java NIO Path
    • Java NIO File
    • Java NIO Scatter/Gather
    • Java NIO SocketChannel
    • Java NIO Selector

Java NIO Selector

By Priya PedamkarPriya Pedamkar

What is Java NIO Selector?

Java NIO Selector is mainly used for Non-blocking IO operation as a multiplexor, for reading ready data and Buffer Oriented approach, for shifting forth and back in the buffer as per the requirement of some exceptional kind of selective channels.

It is meant to inspect single or multiple NIO Channel as well as to regulate which particular channel is prepared for reading or writing i.e. communication. Basically, a selector is introduced to control many channels via an individual thread. Thus, it requires minimum threads for regulating the channels. For operating systems, it is costly to alter between the threads, therefore, this Java NIO Selector is used to enhance the productivity of the system.

Java NIO Selector

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Key Takeaways

  • Java NIO Selector supports various transactions to and from the channels as well as the buffer.
  • We can get the instance of the selector by calling the method open(), which is its static method.
  • This helps to support a distinct thread for managing multiple network connections. Thus, helps operating systems and CPUs to perform better for multitasking.

How to Use Java NIO Selector?

  • Java NIO i.e. New Input/Output, is defined as a high-performance networking and structure and file handling API that functions as an alternation IO API for Java.
  • If you all know about threads or might be friendly to it, then one should have information that it is a costly procedure to context-switch between thread since a thread comprises the core operating system. Generally, we consider the thread as a new procedure that put away a bit of memory ultimately. Therefore, if one uses fewer threads, then it is considered as a better option. But if you have a new OS, then it will not be a big problem to context-switch threads because it is better at multitasking with new versions.
  • Using Java NIO Selector, one can implement an individual thread for handling various channels, so that no multiple threads are created to handle many channels.

Setup Package

  • We do not require any special setup for using Java NIO selector. This selector is a section of the java core package java.nio where all the required classes are available, so one just needs to import these as per requirement.
  • Once registration is completed, then using the selector object, one may register various channels. When any NIO activity occurs related to these registered channels, then, it will be notified by the Selector API. In this way, users are able to read from multiple data sources using an individual thread.
  • For registration of any channel using a selector, it should be a sub-class of SelectableChannel. Hence, these channels are a special kind that is placed in non-blocking mode. This is performed by the following code for registering the channel.
channel.configureBlocking(false);
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);

How to Create Java NIO Selector?

Java NIO Selector is created when the static Selector. open() method is called, belonging to the selector class that will implement the default selector provider of the system for building a new selector. The code line goes like this.

Selector selector = Selector.open();

The selector can even be created when it is invoked by the openSelector() method belonging to the custom selector provider. The selector will stay open with the open method until we close it using the close method.

SelectionKey Objects

While registering the channel using selector, we have seen that the method register() will provide a Selectionkey object, which has a few properties as:

The interest set: It helps to select events that one is interested in selecting using SelectionKey and the following code:

int interestSet = selectionKey.interestOps();
boolean isInterestedInConnect = (interestSet & SelectionKey.OP_CONNECT;
boolean isInterestedInAccept = interestSet & SelectionKey.OP_ACCEPT;
boolean isInterestedInWrite = interestSet & SelectionKey.OP_WRITE;
boolean isInterestedInRead = interestSet & SelectionKey.OP_READ;

The Channel + The Selector: These two interesting properties work together to access the channel + selector object property from the SelectionKey, which is trivial.

Selector selector = sKey.selector();
Channel channel = sKey.channel();

The ready set: It is the collection of operations for which the channel is prepared or ready. Accessing the ready set by.

int readySet = selectionKey.readyOps();
selectionKey.isConnectable();
selectionKey.isAcceptable();
selectionKey.isWriteable();
selectionKey.isReadable();

An attached object: It is an optional one. It is useful for attaching information further to the channel with the object or a manageable process of diagnosing a provided channel, like this:

sKey.attach(theObject);
Object object = sKey.attachment();

SelectionKey Methods for Java NIO Selector

Further, the SelectionKey consists of a few methods described below:

  • Channel(): Getting the channel with the key created.
  • Attachment(): Retaining the attached object.
  • Attach(): Attaching an object to the key.
  • isValid(): Resulting a valid key.
  • selector(): Getting the selector.
  • isWritable(): Stating if the key’s channel is prepared to write or not.
  • isReadable(): Defining if the key’s channel is prepared to read or not.
  • isAcceptable(): Stating if the key’s channel is prepared to connect or accept any incoming new connection or not.
  • interestOps(): Fetches this key’s interest set.
  • isConnectable(): Testing if the key’s channel has completed or failed to complete its operation of socket connection.
  • readyOps(): Fetches the ready set, which is a set of operations the channel is prepared for.

Select Method

Select Method is a static method that is called when we want to select any channel from the selector. This Java NIO selector method select() has been overloaded by:

  • select(): It helps to block the current thread for the time when at least a channel is prepared for the events for which it is registered.
  • select(long timeout): It functions similarly to the select() method except blocking the thread provided for a maximum of timeout milliseconds (i.e. the parameter).
  • selectNow(): It does not perform blocking at all, but rather it will provide instantly whatever channel is prepared.

Also, in case we want to leave a blocked thread that invokes out the select method, then we need to call wakeup() method from selector occurrence so that the thread, which is waiting inside the method select(), is then instantly returned.

Benefits of Multiple Channels

  • Being an NIO component, the selector has the ability to examine multiple channels for defining the channels whichever is ready for read and write i.e. the IO operation.
  • It’s of the benefits of this selector is it uses a single thread for controlling multiple channels, which can be said to have multiple network connections in simple terms. So one does not require to create more threads to handle many channels.

Examples

Here, is a client-side code for selector:

Code:

import java.nio.channels.SocketChannel;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.net.InetSocketAddress;
 
public class SocketClientExample {
public static void main (String [] args)
throws IOException, InterruptedException {
 
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 5454);
SocketChannel client = SocketChannel.open(hostAddress);
 
System.out.println("Client sending messages to server...");
}
}

Output:

Java NIO Selector - Client Messages

Conclusion

The Selectors are not only useful to read data, but they are also helpful in listening for incoming network connections as well as in writing data around slow channels. Here, we have discussed the basic knowledge and usage related to the Java NIO selector. Hope you all have understood it and will learn further.

Recommended Article

We hope that this EDUCBA information on “Java NIO Selector” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. Java NIO SocketChannel
  2. Java NIO Scatter/Gather
  3. Java nio ByteBuffer
  4. Java NIO Path
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more