On the Differences and Application Scenarios of BIO NIO and AIO in Java

  • 2021-07-16 02:18:11
  • OfStack

Recently, I have been preparing for an interview. In order to improve my Java level to a higher level, I read the Authoritative Guide of Netty by Mr. Li Linfeng and learned about the development and latest technology of IO by Java. I really benefited a lot. Now I summarize the differences and application scenarios of BIO, NIO and AIO once.

Before that, let's clarify several concepts:

1. Synchronization: When using synchronous IO, Java handles IO reading and writing by itself.

2. Asynchronous: When using asynchronous IO, Java delegates IO reading and writing to OS for processing, and needs to pass the address and size of data buffer to OS. After completion, OS notifies Java for processing (callback).

3. Blocking: With blocking IO, the Java call blocks until the read-write is complete.

4. Non-blocking: When using non-blocking IO, if you can't read and write immediately, the Java call will return immediately. When the IO event distributor notifies that it can read and write, it will read and write continuously until the read and write are completed.

Here's the point (knock on the blackboard!) !

1. BIO: Synchronize and block. The implementation mode of the server is one connection and one thread. One obvious defect of this mode is that the number of client connections is proportional to the number of server threads, which may cause unnecessary thread overhead and seriously lead to server memory overflow. Of course, this situation can be improved by thread pool mechanism, but it cannot eliminate this drawback in essence.

2. NIO: Before JDK 1.4, IO model 1 of Java was BIO, but since JDK 1.4, JDK introduced a new IO model NIO, which is synchronous and non-blocking. However, the implementation mode of the server is one thread for multiple requests, that is, the requests will be registered on the multiplexer Selector, and the multiplexer will start one thread processing when polling the requests connected with IO.

3. AIO: NIO 1.7 released NIO 2.0, which is asynchronous and non-blocking in the true sense. The implementation mode of the server is multiple valid requests for one thread, and the IO requests of the client are completed by OS first and then notify the server application to start thread processing (callback).

Application scenario: BIO is adopted when the number of concurrent connections is small, because it is very simple to program and debug. However, if high concurrency is involved, NIO or AIO should be selected, and a better suggestion is to adopt the mature network communication framework Netty.


Related articles: