Updated February 15, 2023
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.
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:
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.