Talking about how Java's IO and NIO realize multiplexing


Preface


# One, IO definition

IO definition

	 io是输入和输出数据的操作总体接口	

BIO definition

Blocking IO data behavior, the program will always block and wait for completion
Insert picture description here

NIO definition

Java NIO allows you to perform non-blocking IO. For example, the thread can ask the channel to read data into the buffer. When the channel reads data into the buffer, the thread can do other things. Once the data is read into the buffer, the thread can continue processing it. The same goes for writing data to the channel.
Insert picture description here

AIO definition

In this mode, the user will start the process I/O operation in the future, without waiting for the kernel I/O operation to complete, the process will notify the user after the kernel I/O operation is completed.
Insert picture description here

Two, use scenarios

BIO is used when the number of concurrent connections is small, because it is very simple to program and debug, but if it involves high concurrency, you should choose NIO or AIO. A better suggestion is to use the mature network communication framework Netty


Three, expansion

The main components of NIO:

Buffer, an efficient data container, except for Boolean types, all primitive data types have corresponding Buffer implementations.

Channel, similar to file descriptors seen on operating systems such as Linux, is an abstraction used to support batch IO operations in NIO.

File or Socket are generally considered to be a relatively high-level abstraction, while Channel is an abstraction at the bottom of the operating system. This also allows NIO to make full use of the underlying mechanisms of modern operating systems to obtain performance optimization for specific scenarios, such as DMA (Direct Memory Access) and so on. Different levels of abstraction are interrelated, we can get Channel through Socket, and vice versa.

Selector is the basis for NIO to achieve multiplexing. It provides an efficient mechanism that can detect whether there are channels in the ready state among multiple Channels registered on the Selector, thereby realizing single-thread to multi-channel Efficient management.


to sum up

1 Understanding the basic principles is more important than the specific implementation.

Guess you like

Origin blog.csdn.net/aa327056812/article/details/109580685
Recommended