Java NIO why Selector has to work with Channel in non-blocking mode?

Viewed 211

According to this passage, IO Multiplexing can work with file descriptors in both blocking and non-blocking mode: enter image description here

And non-blocking mode is only needed to cooperate with edge-triggered mode: enter image description here

What's more, according to this answer, Java NIO works in lever-triggered mode.

Then why Java NIO Selector requires the channel to be in the non-blocking mode: enter image description here

Thanks to your reply in advance.

1 Answers

The power of java.nio and the Channel comes from the fact that you can watch over multiple sockets in a non-blocking way. In other words, the traditional java.io was a single-thread / single-socket approach with blocking IO calls, whereas java.nio is meant for a usage where you can spawn thousands of socket connection (via channels and selector) without requiring thousands of threads. Here the job of the selector is to help your thread / thread pool read & write from the channels which are ready and connected.

Java Docs for Channel defines it as,

Defines channels, which represent connections to entities that are capable of performing I/O operations, such as files and sockets; defines selectors, for multiplexed, non-blocking I/O operations

Related