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, I will more specifically describe the differences in each part of the narrative table.

IO ? ? ? ? ? ? ? ? NIO

facing the flow? ????? Buffer oriented

blocked io? ????? Non-clogging IO

No??????????????? Selector 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 each time from the stream. Until all bytes are read. They are not cached anywhere. In addition It cannot move data in the stream back and forth. Suppose you need to move the data read from the stream before and after it, you need to cache it to a buffer. Java NIO has a slightly different buffer-oriented approach.

The data is read to a buffer that it processes later. Can be moved back and forth in the buffer if required.

This adds flexibility in the processing process. However, it is also necessary to check if the buffer contains all the data that you need to process.

And. Be sure that when a lot of other data is read into the buffer. Do not overwrite data that has not been processed in the buffer.

clogging and non-clogging IO

Java IO the various flows are clogged.

This means that when a thread calls read () or write () , the thread is blocked until some data is read. Or the data is completely written. The thread can no longer do anything in this period. The non-clogging mode of Java NIO allows a thread to send a request to read data from a channel, but it can only get the data that is available at the moment, assuming that no data is available at the moment. Instead of keeping the thread plugged, the thread can continue to do other things until the data becomes readable. the same is true for non-clogging writing. A thread requests that some data be written to a channel. But there is no need to wait for it to be fully written, and this thread can do something else at the same time. threads typically use the spare time of non-clogging io to perform IO operations on other channels , so a single thread can now manage multiple input and output channels ( channel).

Selector ( Selectors )

Java NIO selectors agree to a separate thread to monitor multiple input channels. You can register multiple channels using a selector, and then use a separate thread to " Select " The channel: These channels already have input that can be processed, or choose which channel is ready to write. Such a 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. The following aspects of your application design may be affected:

1.???? ? the NIO or IO Class of API called.

2.???? data processing.

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

API called

of course. API calls that use NIO look different when using IO . This is not surprising, however, because it is not only read from one inputstream byte to the next . Instead, 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. Suppose you are working on a line-based text stream, such as:

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. Other words. Once the reader.readline () method returns. You'll know that the lines of text have been read out. readline () is blocked until the whole line is read, which is why. You also know that this row includes the name; the second readline () call returns when you know that this line includes age.

As you can see, this handler executes only when new data is read. And know what the data is for each step. Once the executing 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 a NIO implementation 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 of the data you need is in the buffer. What you know is that the buffer includes some bytes, which makes handling a bit difficult.
Suppose the first time read (buffer) after the call, the data read into the buffer is only half a row, for example, "Name:an" , can you handle the data? Obviously not, you need to wait until the entire row of data is read into the cache. Prior to this, no matter what the data processing was meaningless.

So, how do you know if the buffer includes enough data to handle it? Well, you don't know. The found method can only look at the data in the buffer.

As a result, 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. and can make the program design scheme messy.

Like what:

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

bufferfull () method must track how much data is read into the buffer. and return True or false. This depends on whether the buffer is full. Other words. Assuming that the buffer is ready to be processed, the buffer is full.

bufferfull () method to scan the buffer. However, the state must remain the same before the bufferfull() method is called. Assuming no, the next data read into the buffer may not read to the correct location. This is not possible, but it is another issue that needs attention.

assuming the buffer is full, it can be processed. Assuming it is dissatisfied and 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 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 just one (or several) single threads, but at the cost of parsing the data can be more complex than reading from a blocked stream.

Suppose you need to manage thousands of connections that are open at the same time, and these connections are only sending a small amount of data at a time, such as a chat server, to implement NIO the server may be an advantage. Same. Let's say you need to maintain a lot of open connections to other computers, such as a peer Network. Use a separate thread to manage all your outbound connections. May be an advantage.

The design of multiple connections for a thread, for example, as seen in:


Java NIO: single thread to manage multiple connections

Suppose you have a small number of connections using very high bandwidth. Sending a large amount of data at one time may be a good fit for a typical IOServer implementation. Illustrates a typical IOServer 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.