Java NiO 14, Java NiO vs. IO

Source: Internet
Author: User

Last update time: 2014-06-23

When learning Java NIO and IO APIs, a problem quickly emerges in our minds:

When should I use IO and when should I use NIO?

In this article I will try to write out the different places between NiO and Io, their usage scenarios, and how they affect your code design.

The main differences between Java NiO and IO

The table below summarizes the main differences between Java NiO and IO. I'll give you a more detailed explanation of the differences in this table.

Io Nio
Stream-based Buffer-based
Blocking IO Non-clogging IO
Selectors (selector)

A stream-based relative buffer-based

The first major difference between Java NiO and Io is that IO is stream-based, and NiO is buffer-based. What does that mean?

Stream-based Java IO means that you are reading one or more bytes from one stream at a time. Processing this read-through byte depends on you. They can't be cached anywhere. Also, the data in the stream you cannot forward or return. If you need to go forward or go back and read the data in a stream, you will first need to cache it in buffer.

Java NiO is slightly different in its buffer-based approach. The data is read into a buffer and then processed later. You can move forward or back in the buffer as you want. This medium-processing period gives greater flexibility. However, you also need to check if the buffer contains all the data you need to process. Also, you need to confirm when you can read more data into the buffer, and you cannot overwrite the data that has not been processed by the buffer.

Clogging relative non-clogging IO

The various streams of Java Io are blocked. That means that when a thread calls the Read () method or the Write () method, that thread will be blocked until there is data to read, or the data can be written. During this time, this thread cannot do anything else.

The non-clogging mode of Java NIO allows a thread to send a read data request from one channel and just get the current available, or if no data is currently available, there is nothing. Instead of keeping it locked until there is data to read, the thread can continue to do other things.

The same is true for non-clogging writes. A thread can send a request to write data to a channel, but not wait until it is completely written. This thread then continues to do other things at the same time.

Where do threads spend their free time when non-blocking IO calls? The IO is usually executed concurrently in the other channels. That is, a single thread can manage the inputs and outputs of multiple channels.

Selector (selectors)

The Java NiO selector allows a single thread to monitor input from multiple channels. You can register multiple channels with a selector and then use a single thread to "select" the channel for which the process has input, or "select" the channel that is ready to write. This selector principle makes it easier for a single thread to manage multiple channels.

How NiO and IO affect application design

Whether you choose NiO or IO as your toolkit may affect all aspects of your app's design:

    1. For API calls to NIO or IO classes.
    2. Processing of data.
    3. Number of threads processing data
API callsThe use of NIO, of course, looks different for API calls that use IO. There's nothing to be surprised about. Java NiO is not a byte-by-byte read from a InputStream, for example, and this data must first be read into the buffer and then processed from the buffer. Processing of dataWhen using a purely NIO design relative to the IO design, the processing of the data is also affected. In an IO design, you read bytes of data from InputStream or in a reader. Think about the flow of lines that you're working with text-based data. For example:
Name:annaage:25email: [Email protected]phone:1234567890
This text stream can be processed like this:
InputStream input = ...; Get the InputStream from the client socketbufferedreader reader = new BufferedReader (new InputStreamReader (input)); String nameline   = Reader.readline (); String AgeLine    = Reader.readline (); String emailline  = Reader.readline (); String phoneline  = Reader.readline ();
Notice how the state of this processing is determined by the degree to which the program has been executed. In other words, once the first Reader.readline method returns, you know exactly where the full line of the text has been read. This readline method is blocked until a full line is read. You will also know that this line contains a name. Similarly, when the second ReadLine method call returns, you know that this line contains the age and so on. As you can see, this program will only continue when there is new data to read, and for each step, you know what the data is. Once an executing thread has read a segment of the data in the code, the thread will not go backwards in the data (most of it will not). This principle is the same as illustrated in the following illustration:
The implementation of a NIO will look different. Here's a special example:
Bytebuffer buffer = bytebuffer.allocate, int bytesread = inchannel.read (buffer);
Note the second line, which reads the bytes from the channel into the Bytebuffer. When that method call returns, you don't know if you need all the data in this buffer. All you know is that this buffer contains some bytes. This will make handling a little difficult. Imagine that, if the first read (buffer) is called, all the data read to the buffer is half the line. For example, "Name:an". Can you handle that data? No, really. You need to wait until a complete data row is read into the buffer before any part of the data is meaningfully processed. How do you know that the buffer contains enough data in order to be able to manipulate the data meaningfully? Well, you don't know. The only way to find out is to look at the data in this buffer. The result is that you may have to check the data in this buffer several times before you know if all the data is here. This is not only inefficient, but also confusing in terms of code design. For example:
Bytebuffer buffer = bytebuffer.allocate, int bytesread = inchannel.read (buffer), while (Bufferfull (bytesread)) {    bytesread = inchannel.read (buffer);}
The Bufferfull () method has to track how much data is 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 full. This bufferfull () method scans the buffer, but must be in the same position as the buffer before the Bufferfull () method is called. If not, the next data read to Buffe may not be read in the correct location. This is not an impossible thing, but this is still another problem to be aware of. If the buffer is full, it can be processed. If you are dissatisfied, if that makes sense in your particular scene, you may not be able to manipulate the data in part, regardless of what data is here. In most scenarios it is not possible. The process is as follows:
SummaryNIO allows you to manage multiple channels (network connections or files) using a single thread or multiple threads, but the cost is that parsing data can be slightly more complex relative to reading data from a clogged stream.
If you need to manage thousands of open connections at the same time, each of these connections will send some data, such as a chat server, it might be an advantage to implement this server with NiO. Similarly, if you need to keep a lot of open connections to other computers, such as one in a peer network, using a separate thread to manage all of your external connections may be an advantage. For this one thread, multiple connections are designed as shown in the following:
If you have very few connections with very high bandwidth, sending lots of data each time, a standard IO implementation may be a better choice. As shown in the following:

Translation Address: http://tutorials.jenkov.com/java-nio/nio-vs-io.html

Java NiO 14, Java NiO vs. IO

Related Article

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.