Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java NIO, is a selector useful for a client SocketChannel?

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?

like image 633
Arvanem Avatar asked Sep 09 '12 10:09

Arvanem


People also ask

What is selector in Java NIO?

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.

How does NIO work in Java?

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.

How do you create a selector in 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.

What is Java NIO channel?

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.


2 Answers

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.

like image 117
user207421 Avatar answered Nov 15 '22 22:11

user207421


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.

like image 36
Sergey Kalinichenko Avatar answered Nov 15 '22 22:11

Sergey Kalinichenko