Java NIO Series Tutorials (12) Java NiO and IO

Source: Internet
Author: User

Original address: http://tutorials.jenkov.com/java-nio/nio-vs-io.html

author : Jakob Jenkov translator : Guo proofreading: Fang Fei

After learning the APIs for Java NIO and Io, a problem immediately poured into my mind:

When should I use IO and when do I use NIO? 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.

The main differences between Java NiO and IO

The following table summarizes the main differences between Java NiO and Io, and I'll describe in more detail the differences in each section of the table.

IO NIO oriented stream oriented buffer blocking IO  non-blocking IO no                selector
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. 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

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 during this time. The non-blocking mode of Java NIO enables a thread to send requests to read data from a channel, but it can only get the data that is currently available and will not get anything if no data is available. Instead of keeping the thread blocked, the thread can continue to do other things until the data becomes readable. The same is true for non-blocking writes. 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 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).

Selector (Selectors )

The 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 to "select" the channel: 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.

how NiO and Io affect the design of applications

Whether you choose IO or the NIO toolbox, you may have an impact on the following aspects of your application design:

    1. API calls to the NIO or IO classes.
    2. Data processing.
    3. The number of threads used to process the data.
API calls

Of course, using NIO's API calls may look different than using IO, but it's not surprising that the data must be read into the buffer before it is not read from only one inputstream.

Data Processing

Data processing is also affected by the use of purely nio designs compared to IO designs.

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

Name:annaage:25email: [Email protected]phone:1234567890

The flow of this line can be handled like this:
InputStream input = ...; Get the InputStream from the client socket

1 BufferedReader reader = newBufferedReader(newInputStreamReader(input));
2
3 String nameLine   = reader.readLine();
4 String ageLine    = reader.readLine();
5 String emailLine  = reader.readLine();
6 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). Also illustrates this principle: (Java IO: Reading data from a blocked stream ) and a NIO implementation will be different, here is a simple example:

1 ByteBuffer buffer = ByteBuffer.allocate(48);
2
3 intbytesRead = inChannel.read(buffer);

Note the second line, which reads bytes from the channel to 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.
Assuming that after the first read (buffer) call, the data that is read into the buffer is only half a line, for example, "Name:an", can you process 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:

1 ByteBuffer buffer = ByteBuffer.allocate(48);
2
3 intbytesRead = inChannel.read(buffer);
4
5 while(! bufferFull(bytesRead) ) {
6
7 bytesRead = inChannel.read(buffer);
8
9 }

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

The Bufferfull () method scans the buffer, but must remain the same state before the Bufferfull () method is called. 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: Reads 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 data can be more complex than reading data from a blocking stream.

If you need to manage thousands of connections that are open at the same time, these connections can only send a small amount of data, such as a chat server, to implement NIO's servers as 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-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 once, perhaps a typical IO server implementation might be very fit. Illustrates a typical IO server design:

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

original articles, reproduced please specify: reproduced from the Concurrent programming network –ifeve.com This article link address: Java NIO Series Tutorials (12) Java NiO and IO

Java NIO Series Tutorials (12) 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.