The difference between IO and NiO in Java __java

Source: Internet
Author: User
Tags readline

First, the concept

NiO is the new IO, the library is introduced in JDK1.4. NiO and IO have the same effect and purpose, but the implementation is different, NIO is mainly used in blocks, so the efficiency of NIO is much higher than IO. Two sets of NIO are provided in the Java API, one for standard input output NIO and the other for network programming NiO.

Ii. the main differences between NIO and IO

The following table summarizes the main differences between Java IO and NiO:

Io Nio
Stream oriented Buffer-oriented
Blocking IO Non-blocking IO
No Selector

1. Flow-oriented and buffer-oriented

The first major difference between Java io and NiO is that IO is stream-oriented and NIO is buffer-oriented. Java io-oriented streaming means that one or more bytes are read from the stream each time, until all bytes are read, and they are not slowed down anywhere. In addition, it cannot move data back and forth in the stream. If you need to move data that is read from the stream before and after, you need to first cache it to a buffer. Java NiO has a slightly different buffer-oriented approach. The data is read to a buffer it handles later, and can be moved back and forth in the buffer when needed. This increases the flexibility in the processing process. However, you also need to check whether the buffer contains all the data you need to work with. Also, make sure that when more data is read into the buffer, do not overwrite data that has not been processed in the buffer.

2. Blocking and non-blocking IO

The various streams of Java Io are blocked. This means that when a thread calls read () or write (), the thread is blocked until some data is read, or the data is fully written. The thread can no longer do anything in the meantime. Non-blocking mode for Java NiO, causes a thread to send requests to read data from a channel, but it can only get the data that is currently available, and if no data is currently available, nothing gets done, rather than keeping the thread blocked, so that the thread can continue to do something else until the data becomes readable. The same is true for non-blocking writing. A thread requests to write some data to a channel, but does not need to wait for it to be fully written, and the thread can do something else at the same time. Threads typically use non-blocking IO idle time to perform IO operations on other channels, so a single thread can now manage multiple input and output channels (channel).

3, selector (selectors)

The Java NiO selector allows 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 the input that can be processed, or select the channel that is ready to be written. This selection mechanism makes it easy for a single thread to manage multiple channels.

Iii. how NIO and IO affect application design

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

1. API calls to NiO or IO classes.
2. Data processing.
3. Number of threads used to process data.

1, API call

Of course, the API call using NIO may look different from using IO, but that's not surprising, since it's not just read from one inputstream to bytes, but the data must be read into the buffer before it is processed.

2. Data processing

Data processing is also affected by the use of pure NIO design compared to IO design.

In IO design, we read the data byte by bit from InputStream or reader. Let's say you're working on a line based text stream, such as:

Name:anna 
age:25
email:anna@mailserver.com 

The flow of this line can be handled in this way:

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  

Please note how long the processing status is determined by the program execution. In other words, once the Reader.readline () method returns, you will know that the line of text has been read, ReadLine () blocked until the whole line is read, that's why. You also know that this row contains a name; Similarly, the second readline () call returns when you know that the line contains age and so on. As you can see, the handler runs only when new data is read and knows what the data for each step is. Once a running thread has processed some of the data that is being read, the thread does not rollback the data (mostly). The following figure also illustrates this principle:

The implementation of a NIO is different, and here's a simple example:

Bytebuffer buffer = bytebuffer.allocate (48); 

Note that the second line reads bytes from the channel to Bytebuffer. When this method call returns, you don't know if 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. Assuming that after the first read (buffer) call, the data read into the buffer is only half a row, for example, "Name:an", can you process the data. Obviously not, you 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 discovered 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 (in);   

int bytesread = inchannel.read (buffer);   

while (! bufferfull (Bytesread)) {   
       bytesread = inchannel.read (buffer);   

The Bufferfull () method must track 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.

The Bufferfull () method scans the buffer, but must remain the same state before the Bufferfull () method is invoked. If not, the next data read into the buffer may not be able to read to the correct location. This is not possible, but it is another issue that needs to be noted.

If the buffer is full, it can be processed. If it is dissatisfied and meaningful in your actual case, you may be able to process some of the data. But in many cases this is not the case. The following figure shows the "Buffer data Loop Ready":

Iv. Summary

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

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

Java NIO: Single-threaded management of multiple connections

If you have a small number of connections that use very high bandwidth and send a large amount of data at one time, perhaps a typical IO server implementation might be very much in agreement. The following figure illustrates a typical IO server design:

Java io: A typical IO server design-a connection is handled through a single thread.

Reprint Source: https://www.cnblogs.com/xiaoxi/p/6576588.html

Reference Link: http://www.jasongj.com/java/nio_reactor/

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.