Comparative Analysis of NIO and IO in Java

Source: Internet
Author: User

In general, there are three main differences between IO and NIO in java:

IO NIO
Stream-oriented Buffer-oriented
Blocking IO Non-blocking IO
None Selectors)

1. Stream-oriented and buffer-oriented

The first major difference between Java NIO and IO is that IO is stream-oriented and NIO is buffer-oriented. Java IO stream orientation means that one or more bytes are read from the stream each time until all bytes are read, and they are not cached anywhere. In addition, it cannot move data in the stream before and after. If you need to move the data read from the stream before and after, you must first cache it to a buffer zone. The buffer-oriented method of Java NIO is slightly different. The data is read to a buffer that will be processed later. When necessary, it can be moved before and after the buffer. This increases the flexibility in the processing process. However, you also need to check whether the buffer contains all the data you need to process. In addition, make sure that when more data is read into the buffer, do not overwrite the unprocessed data in the buffer.

2. Blocking and non-blocking IO

Various Java IO streams are blocked. This means that when a thread calls read () or write (), the thread is blocked until some data is read or completely written. This thread can no longer do anything during this period. The non-blocking mode of Java NIO enables a thread to send requests from a channel to read data, but it can only obtain currently available data. If no data is available, you won't get anything. Instead of keeping the thread congested, the thread can continue to do other things until the data becomes readable. This is also true for non-blocking writes. A thread requests to write some data to a channel, but does not need to wait for it to write completely. This thread can also do other things. Threads usually use the idle time of non-blocking IO to execute IO operations on other channels, so a separate thread can now manage multiple input and output channels ).

3. Selectors)

Java NIO selector allows a single thread to monitor multiple input channels. You can register multiple channels and use one selector. Then, you can use a separate thread to select a channel: there are input that can be processed in these channels, or select the channel to be written. This selection mechanism makes it easy for a single thread to manage multiple channels.


The following describes the respective advantages of blocking and non-blocking:

Generally, a file or device specified by a file descriptor can work in two ways: blocking and non-blocking. Blocking means that when you try to read and write the file descriptor, the program enters the waiting state if there is nothing to read at the time or it cannot be written at the moment, until something is readable or writable. For non-blocking states, if nothing is readable or not writable, the read/write function returns immediately without waiting.

In traditional socket IO, you need to create a thread for each connection. When the number of concurrent connections is very large, the stack memory occupied by the thread and the overhead of CPU thread switching will be huge. This method has a high response speed and is easy to control. It is very effective when the number of connections is small, however, generating a thread for each connection is undoubtedly a waste of system resources. If there are many connections, there will be insufficient resources.

With NIO, you no longer need to create separate threads for each thread. You can use a thread pool containing a limited number of threads or even a thread to serve any number of connections. Since the number of threads is smaller than the number of connections, each thread cannot be blocked when performing IO operations. If it is blocked, some connections will not be processed. NIO provides this non-blocking capability.

How can a small number of threads serve a large number of connections at the same time? The answer is "ready. This is like a meal at a restaurant. Every table of guests has a waiter dedicated to serving you, from you to the restaurant to checkout, the advantage of this method is that the quality of service is good, one-to-one service, VIP, but its shortcomings are also obvious, and the cost is high. If the restaurant business is good and there are 100 guests at the same time, 100 waiters are required, the boss was heartbroken when he sent his salary. This is a traditional way to connect a thread.

Who is the boss. The boss figured out how to use ten waiters to serve 100 guests at the same time. The boss found that the waiters were not always busy serving the guests, after the guests have ordered the food and finished the food, the waiter will be idle during this period of time. However, this waiter is still occupied by the guests and cannot serve other guests, in the words of Huawei leaders, the work is not full. So how can we take advantage of this idle time. The restaurant owner thought of a way to ask a waiter (front-end) to collect the requirements of the guests and register them. For example, if a guest comes in and order to order, the guest will settle the bill, records are sorted in order. Every waiter can pick up a requirement here, such as ordering food, and take the menu to help the guests order food. After ordering the food, the waiter will be back immediately to receive the next requirement and continue to serve other guests. In this way, the service quality is not as good as one-to-one service. When there is a lot of data, you may have to wait. But the benefits are also obvious. As the waiter does not have to be idle while the guest is eating, the waiter can serve other guests during this time, in the past, 10 waiters served a maximum of 10 guests at the same time. Currently, they may serve 50 and 60 guests.

There are two differences between this service method and the traditional one:

1. added a role for someone responsible for collecting customer requirements. The corresponding information in NIO is Selector.

2. Change the blocking service mode to non-blocking service. When the guests are eating, the waiter does not have to stay with the guests all the time. For traditional I/O operations, such as read (), when no data is readable, threads are blocked until the data arrives. When there is no readable data in NIO, read () will immediately return 0, and the thread will not be blocked.

The cornerstone behind NIO design: Reactor mode, an architecture model for event Multi-Channel Separation and allocation. In NIO, after the client creates a connection, it first needs to register the connection to Selector, which is equivalent to telling the front-end that you want to eat after the guests enter the restaurant, the front-end will tell you the number of your table, and then you may sit down at that table. SelectionKey is the table number. When a table needs services, the front desk will record which table needs services, such as the main dishes at table 1, the checkout at table 2, and the waiter will take a record from the front desk, provide services based on the record, and then take the next one. In this way, the service time is used most effectively.

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.