The main differences between Java NiO and IO

Source: Internet
Author: User

when should I use IO , when to use NIO it? In this article, I'll try to clearly parse the differences between Java NIO and IO , their usage scenarios, and how they affect your code design.

Java NIO and the IO The main difference

The following table summarizes Java NIO and the IO The main difference between, I will describe in more detail the differences in each part of the table.

IO NIO

Stream -oriented buffering

blocking IO non-blocking IO

No Selector

Stream-oriented and buffer-oriented

Java NIO and the IO The first biggest difference between the two is that IO is flow-oriented, NIO is buffer-oriented. the Java IO - oriented stream means that one or more bytes are read from the stream every time, until all bytes are read, and they are not being slowed anywhere. In addition, it cannot move data in the stream back and forth. If you need to move the data read from the stream before and after it, you need to cache it to a buffer first. Java NIO has a slightly different buffer-oriented approach. The data is read to a buffer that it processes later, and can be moved back and forth in the buffer if needed. This increases the flexibility of the process. However, you also need to check if the buffer contains all the data that you need to process. Also, make sure that when more data is read into the buffer, do not overwrite the data that has not been processed in the buffer.

blocking and non-blocking IO

java IO read () write () Java NIO non-blocking writes as well. A thread requests to write some data to a channel, but does not have to wait for it to be fully written, and the thread can do something else at the same time. threads are typically non-blocking io idle time is used to perform on other channels. io operation, so a separate thread can now manage multiple input and output channels ( channel

Selector ( Selectors )

Java NIO selector allows a single thread to monitor multiple input channels, you can register multiple channels using a selector, and then use a separate thread " Select " Channels: These channels already have inputs that can be processed, or select the channels that are ready to be written. This selection mechanism makes it easy for a single thread to manage multiple channels.

NIO and the IO How to influence the design of an application

Whether you choose IO or NIO Toolbox, which may affect the following aspects of your application design:

1. API calls to NIO or IO classes .

2. data processing.

3. The number of threads used to process the data.

API called

of course, using NIO of the API called when it looks like using the IO is different, but it's not surprising, because it's not just a InputStream Read bytes, but the data must be read into the buffer before processing.

Data processing

use a purely NIO Compared with the design IO design and data processing are also affected.

in the IO in the design, we InputStream or Reader reads data byte by bit. Let's say you're working on a line-based text stream, for example:

Name:anna

Age:25

Email: [Email protected]

phone:1234567890

The flow of this line can be handled like this:

InputStream input = ...; Get the InputStream from the client socket
BufferedReader reader = new BufferedReader (new InputStreamReader (input));
String nameline = Reader.readline ();
String ageline = Reader.readline ();
String emailline = Reader.readline ();
String phoneline = Reader.readline ();

Note how long the processing status is determined by the program execution. In other words, once the reader.readline () method returns, you know that the text line is read and readLine () blocks until the entire line is read, which is why. You also know that this row contains the name; again, the second readline () call returns, and you know that this line contains age. As you can see, the handler runs only when new data is read, and knows what the data is for each step. Once a running thread has processed some of the data that is being read, the thread will no longer roll back the data (mostly so). It also illustrates this principle:


( Java IO: reading data from a blocked stream )

and the implementation of a NIO will be different, here is a simple example:

Bytebuffer buffer = bytebuffer.allocate (48);
int bytesread = inchannel.read (buffer);

note the second line, reading bytes from the channel to the Bytebuffer . When this method call returns, you do not know whether all the data you need is in the buffer. What you know is that the buffer contains some bytes, which makes handling a bit difficult.
Suppose the first time read (buffer) after the call, the data that is read into the buffer is only half a row, for example, "Name:an" , can you handle the data? Obviously, there is no need to wait until the entire row of data is read into the cache, before any processing of the data is meaningless.

So, how do you know if the buffer contains enough data to handle it? Well, you don't know. The found method can only view the data in the buffer. The result is that you have to check the buffer data several times before you know that all the data is in the buffer. This is not only inefficient, but also can make the program design scheme messy. For example:

Bytebuffer buffer = bytebuffer.allocate (48);
int bytesread = inchannel.read (buffer);
while (! bufferfull (bytesread)) {
Bytesread = inchannel.read (buffer);
}

bufferfull () The method must keep track of how much data is read into the buffer and return TRUE or false, depending on whether the buffer is full. In other words, if the buffer is ready to be processed, it means that the buffer is full.

bufferfull () method to scan the buffer, but must remain in the Bufferfull () method is called before the same state. If not, the next data read into the buffer may not read to the correct location. This is not possible, but it is another problem to be aware of.

if the buffer is full, it can be processed. If it is dissatisfied and is meaningful in your actual case, you may be able to handle some of the data. But in many cases this is not the case. Shows " buffer data Loop ready ":


Java NIO: read the data from one channel until all the data is read into the buffer. .

3) number of threads used to process data

NIO allows you to manage multiple channels (network connections or files) using only one (or several) single threads, but the cost is that parsing the data can be more complex than reading the data from a blocking stream.

If you need to manage thousands of connections that are open at the same time, these connections send only a small amount of data, such as a chat server, to implement NIO server may be an advantage. Similarly, if you need to maintain many open connections to other computers, such as a peer -to network, using a separate thread to manage all your outbound connections may be an advantage. The design of multiple connections for a thread is as follows:


Java NIO: single thread to manage multiple connections

If you have a small number of connections using very high bandwidth, sending large amounts of data at once, perhaps typical IO The server implementation may be very fit. Illustrates a typical IO Server design:


Java IO: a typical IO Server Design - a connection is handled by a thread .


The main differences between Java NiO and IO

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.