Java NiO and IO

Source: Internet
Author: User

When learning Java NIO and IO APIs, a problem quickly emerges in the brain:

When to use IO? When to use NiO?

The author of this article will try to clarify some of the differences between Java NiO and Io, their use cases, and how they each affect our code design.

The main differences between Java NIO and IO

The following table briefly describes the differences between NIO and Io, and then we will detail each of the different points in the table.

Io Nio
Streaming (stream oriented) Buffered (buffer oriented)
Blocking IO Non-blocking IO
Selector (selectors)
stream-oriented and buffered

The first big difference between Java NiO and Io is that IO is flow-oriented, and NIO is buffer-type. So, what the hell does that mean?

Java IO is flow-oriented, which means that we read one or more bytes at a time from one stream. It is up to us to decide what to do with the bytes read, which does not have any caches. In addition, we cannot move back and forth in the data stream, and if we want to move back and forth from the data read from the stream, we need to first cache the data into a buffer.

Java NiO has a slightly different buffering method. Data is processed after it is read into the buffer, and we can move back and forth in the data as needed. This provides flexibility for processing, but in order to fully handle all the data we also need to check whether the buffer contains all the required data, and we need to make sure that the data that is not processed when more data is read into the buffer cannot be overwritten.

blocking io and non-blocking io

The various streams of Java io are blocking types. This means that when a thread calls the Read () method or the Write () method, the thread will remain blocked until the data is read or the data is fully written, and the thread cannot do anything else while it is blocked.

The non-blocking mode of Java NIO allows a thread to request read data from a channel, which will only fetch data that is currently valid or not currently valid, rather than blocking until the data is ready to be read, while the thread can do other things.

This process is also true for non-blocking data writes. A thread can write some data to the channel, but not wait for the data to be fully written. The thread can continue to do other things at the same time after the request has been completed.

When threads are not blocked on Io calls, their idle time is usually spent performing IO operations on other channel. In other words, a thread can manage multiple input and output channel.

selector (selectors)

Selector in Java NiO allows a thread to monitor the input of multiple channel. We can register multiple channel on a selector and then use a thread "select" to enter the available channel for processing, or select the channel to be written. This selector pattern makes it very easy for a single thread to manage multiple channel changes.

effects of NIO and IO on application design

Whether we choose NiO or IO as our IO toolkit, it is possible to influence the design of the application in the following ways:

    1. Calls to NiO or IO API classes

    2. Processing of data

    3. Number of threads used to process data

API calls

Of course, the invocation of the NIO API is not the same as IO, which is nothing to be surprised about. Unlike IO, which reads data from one byte in a stream, such as InputStream, when using NIO, the data must be read into a buffer before it is processed from the buffer.

Data Processing

Data processing is also affected when designing and using the IO design with NIO.

IO Design We read data from InputStream or reader in a byte-by-byte. Let's say we're dealing with a stream-based text data, such as:

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

Use the stream to process this text code as follows:

Iinputstream input = ...; Get Theinputstream from the client socketbufferedreader reader = Newbufferedreader (new InputStreamReader (input)); String nameline = Reader.readline (); String ageline = Reader.readline (); String emailline = Reader.readline (); String phoneline = Reader.readline ();
Note that the processing state is determined by how far the program executes. In other words, once the first Reader.readline () method returns, we can know that the complete line of text reads is complete; the ReadLine () method remains blocked until the line is read, which is the reason; this line contains the name information. Similarly, when the second line of the ReadLine () method returns, we get the age information, and so on.

As we can see, this program only executes when new data is readable, and at each step we know what data is read; Once the execution thread has read some data forward in the code, the thread will not be able to rewind in the data (most of the time). The rule:

Figure 1:java IO reads data from the blocking stream

The implementation of NIO is different, here is the code example:

Bytebuffer buffer =bytebuffer.allocate, int bytesread = inchannel.read (buffer);
Note that the second line reads the byte code from the channel toward Bytebuffer. When the method call returns, we don't know if all of the data we need is already inside the buffer. All we know is that the buffer contains some bytes. This makes processing more difficult at a certain level.

Assume that if the data is read to the buffer after the first read (buffer) is only half a row. For example, "Name:an". Can we handle this data? No. We need to wait until at least one full row of data has been read into the buffer, and it is meaningless to process the data before reading the full line.

So how do we know if the buffer contains enough data to meet the processing requirements? I don't know. The only workaround is to look at the data in the buffer. This will cause us to have to check the data in the buffer multiple times to confirm that the data is fully read into the buffer. This approach is inefficient and can lead to confusing programming. For example:

Bytebuffer buffer = bytebuffer.allocate, int bytesread = inchannel.read (buffer), while (Bufferfull (bytesread)) { Bytesread = inchannel.read (buffer);}
The Bufferfull () method keeps track of how much data has been read to the buffer, and returns TRUE or false depending on whether the buffer is full. In other words, if the buffer is ready to be processed, it is considered complete.

Although the Bufferfull () method scans the buffer, it leaves the buffer in the same state before it is called. If the status is not the same, then the data read into the buffer may not be read in the correct location. This is not impossible, but this is another issue to be aware of.

If the buffer is intact, then it can be processed. If not complete, we may be able to partially process the data already in the buffer, if allowed in a particular scenario. In most cases this situation is not allowed.

If the "data in buffer is ready" logic is shown:

Figure 2:java NIO reads data from the channel until all data is in the buffer

Summary

NIO allows the use of a single (or small) number of threads to manage multiple channel (network connections or files), but at the expense of parsing data more complex than using blocking streams to read data.

If you need to manage thousands of connections at the same time, and each connection is just sending a small amount of data, such as a chat server, using NIO is a better advantage. Similarly, if you need to keep a lot of connections and other machines connected, such as peer-to network, it might be appropriate to use single-threaded to manage all connections, as in this single-threaded, multi-connection design:

Figure 3:java NIO A thread manages multiple connections

If very high bandwidth has very few connections to send a lot of data at once, then the classic IO implementation may be the most appropriate. Use the classic IO design diagram as follows:

Figure 4:java IO Classic IO server Design-a connection is handled by a single thread

1. This article is translated by the programmer architecture

2. This article is translated from Http://java.dzone.com/articles/java-nio-vs-io

3. Reprint please be sure to indicate this article from: Programmer Architecture (No.:archleaner )

4. More articles please scan the code:

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.