In Java NIO, it is easily understandable why a ServerSocketChannel must have a selector. The selector can check from among several client channels which is ready for I/O operations.
However, in some commentary I have read on the web, the selector mechanism is applied to the client SocketChannel. I don't understand why a selector is of use to a client. Can anyone explain why it is of use in the usual circumstance where there is only one server?
The Java NIO Selector is a component which can examine one or more Java NIO Channel instances, and determine which channels are ready for e.g. reading or writing. This way a single thread can manage multiple channels, and thus multiple network connections.
Java NIO works as the second I/O system after standard Java IO with some added advanced features. It provides a different way of working with I/O than the standard IO. Like Java.io package which contains all the classes required for Java input and output operations, the java.
A selector may be created by invoking the open method of this class, which will use the system's default selector provider to create a new selector. A selector may also be created by invoking the openSelector method of a custom selector provider. A selector remains open until it is closed via its close method.
In Java NIO, the channel is a medium used to transports the data efficiently between the entity and byte buffers. It reads the data from an entity and places it inside buffer blocks for consumption. Channels act as gateway provided by java NIO to access the I/O mechanism.
Unless you're connecting to hundreds of servers, it is difficult to see the point of non-blocking NIO in a client at all. But if you're using non-blocking NIO, you definitely have to use a Selector
, otherwise you can't know when to read the channel, or when it becomes writable again after an incomplete write.
Selectors let you service concurrent communication across multiple channels using a single thread. It may be useful on a client when you must communicate with several servers concurrently, or when you communicate with peer computers in the role of a client, such as when reading a torrent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With