The difference and usage of Java Bio,nio,aio

Source: Internet
Author: User

Java Network IO Programming, from traditional bio (synchronous blocking) to NiO (synchronous non-blocking) to AIO (asynchronous non-blocking).


Scenario: The client wants to send a request to the server, the server will set up a thread response for each client, the problem is, if the client has a delay and other exceptions, more network anomalies, so that the server for its established thread, has been in the waiting state, This thread takes a long time (because the data is prepared and read on this thread), and worse, if there is a large amount of concurrent access at this time, the server will create a large number of threads to respond to it, so that the server resources exhausted.

One, the traditional bio of some problems, bio network programming is the basic model of C/S model, that is, two of the communication between processes.

Server provides IP and listening ports, the client through the connection to the server to listen to the address to initiate a connection request, through three handshake connection, if the connection was successfully established, the two sides can communicate through the socket.

In the traditional development of the synchronous blocking model, ServerSocket is responsible for binding IP address, initiating the listening port, and the socket is responsible for initiating the connection operation. After the connection is successful, both sides communicate through the input and output streams in a synchronous blocking type.

briefly describe the server-side communication model for bio: the service side of the bio communication model, usually by a separate acceptor thread, is responsible for listening to the client's connection, which receives the client connection request, creates a new thread for each client after the link processing has not finished processing, returns the reply to the client through the output stream, and the thread destroys. That is, a typical request one answer overnight model.

At first people in order to solve the above, high concurrency under the server to create too many threads and exhausted, someone came up with a thread pool to control the number of established threads, not the server hangs, so there is a pseudo-asynchronous IO programming

One (1), pseudo-asynchronous I/O programming

In order to improve the model of a connecting thread, we can use the thread pool to manage these threads (see the previous article for more) and implement 1 or more threads to handle N-Client models (but the underlying or used synchronous blocking I/O), commonly referred to as "pseudo-asynchronous i/ O Model ".


We know that if you use the Cachedthreadpool thread pool (no limit on the number of threads, if you are not sure to refer to the articles provided in the first article), in fact, in addition to automatically help us manage the thread (reuse), it looks like a 1:1 of the client: the number of threads model, Using Fixedthreadpool, we control the maximum number of threads, guarantee the control of the limited resources, and realize the n:m pseudo asynchronous I/O model.

However, because the number of threads is limited, if a large number of concurrent requests occur, more than the maximum number of threads can wait until there are idle threads in the thread pool to be reused. when the input stream of the socket is read on the line, it blocks until it occurs:

have data to read

Available data and read complete

Null pointer or I/O exception occurred

so in the slow reading of data (such as large amount of data, slow network transmission, etc.), a large number of concurrent circumstances, other access to the message, can only wait, this is the biggest drawback. NIO, which will be introduced later, will solve the problem.

Ii. NIO Programming (non-blocking I/O)

The new Java I/O library is introduced in the java.nio.* package in the JDK 1.4 to improve speed. In fact, the "old" I/O package has been implemented using NIO again, even if we do not explicitly use NIO programming to benefit from it. Speed increases can occur in both file I/O and network I/O, but this article discusses only the latter.


(1) Buffer buffers

Buffer is an object that contains the data read and written, and in NiO, all data is processed through a buffer. is written to the buffer when the data is written. Any time you access data in NiO, you are operating through a buffer.

The buffer is actually an array structure and provides information on data structure access and the maintenance of read and write locations.

All 8 basic types have corresponding buffers: Bytebuffe, Charbuffer, Shortbuffer, Intbuffer, Longbuffer, Floatbuffer, DoubleBuffer. They implemented the same interface: Buffer.

(2) Channel channel

We read and write the data through the channel, it's like a pipe, it's a channel. the channel is different from the flow where the channel is bidirectional and can be used for reading, writing, and simultaneous read and write operations.

The underlying operating system's channels are generally full-duplex, so Full-duplex channel can better map the underlying operating system APIs than streaming.

There are 2 major categories of channel:

Selectablechannel is used for reading and writing to the user's network (the Serversocketchannel and socketchannel that are involved in the following code are subclasses of Selectablechannel.) )

FileChannel actions for Files

(3) Multiplexing multiplexer Selector

Selector is the foundation of Java NIO programming.

Provides the ability to choose a task that is already in place: Selector will constantly poll channel on it, and if a read or write event occurs on a channel, the channel is in a ready state and will be polled by selector. The Selectionkey can then be used to obtain a set of ready channel for subsequent I/O operations.

A selector can poll multiple channel at the same time because the JDK uses epoll () instead of the traditional select implementation, so there is no limit to the maximum connection handle 1024/2048. Therefore, only one thread is responsible for selector polling and can access thousands of clients.

(4) NiO service end

The main steps to create the NIO server are as follows:

Open Serversocketchannel, listen for client connection binding listening ports, set up connections to create reactor threads for non-blocking mode, create multiplexer and start threads Register the Serversocketchannel on the selector in the reactor thread, monitor the Accept event selector polling-ready key selector Listen to the new client access, handle the new access request, complete the TCP three handshake, Resume Physical Link

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.