The working mechanism and principle of java NIO

NIO stands for non-blocking IO, that is, synchronous non-blocking IO. So what is the difference between NIO and BIO? BIO is synchronous blocking IO, and NIO is synchronous non-blocking IO, that is, it is all its own work to handle it, but NIO is non-blocking, non-blocking IO is when one thing is not completed, you can also do other things , You don’t have to wait for this thing to complete before you can do other things. For example, you have to line up for dinner. BIO has to line up to finish the meal and then do other things. NIO can do other things first and come back later. eat. Having said that, let us look at the NIO-based socket processing process diagram.

The above figure briefly describes the processing process of a socket request based on NIO. In order to understand the whole process, first understand what the selector and channel mean. The selector plays a role similar to the administrator, which can manage multiple channels, and the selector uses selectedKeys. The method can detect whether all the channels registered by the administrator have data to be read. The channel is the data transmission channel of the client and server threads. As long as the channel is registered with the selector, the selector can manage and monitor it.

When the client's request thread and the server establish a connection, and the channel has been registered on the selector, the selector can monitor the I/O status on the channel, and the administrator can check whether the I/O on the channel is through the select() method. It is ready. If the registered channel I/O status has not changed, then the select method will wait to know the timeout. If there are multiple channels with data, the data will be allocated to the corresponding Buffer. In this case, each Connection data interaction is not a blocking mode, so a thread can handle a large number of connection requests at the same time.

Both BIO and NIO are synchronous I/O, so is there any asynchronous I/O? Of course, asynchronous I/O is Asynchronous IO, referred to as AIO. AIO is based on NIO and introduces the concept of asynchronous channels. Unlike NIO, NIO is a thread that continuously checks data by polling. Is it ready? Process it when it is ready. AIO is a function that registers IO monitoring with the operating system, and the operating system completes the IO operation and actively triggers a response.

So what are the applicable scenarios of BIO, NIO, and AIO?

BIO: Applicable to a small and fixed architecture with a small number of connections, used in versions before jdk1.4.

NIO: Applicable to architectures with a large number of connections but relatively short connections. It is supported in jdk1.4.

AIO: It is suitable for the architecture with a large number of connections and is a long connection. It is supported in jdk7.

Guess you like

Origin blog.csdn.net/wzs535131/article/details/103796558