Java NIO vs. IO

Source: Internet
Author: User
Tags readline

When studying both the Java NIO and IO APIs ' s, a question quickly pops into mind:

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

In this text I'll try to shed some light on the differences between Java NIO and IO, their use cases, and how they affec t the design of your code.

Main Differences betwen Java NIO and IO

The table below summarizes the main differences between Java NIO and IO. I'll get into more detail on each difference in the sections following the table.

IO NIO
stream Oriented buffer Oriented
Blocking IO non Blocking IO
  selectors

Stream oriented vs. Buffer oriented

The first big difference between Java NIO and Io are that IO are stream oriented, where NIO is buffer oriented. So, what's does that mean?

Java IO being stream oriented means that you read one or more bytes at a time, from a stream. What does with the read bytes are up to you. They is not cached anywhere. Furthermore, you cannot move forth and back in the data in a stream. If you need to move forth and back in the data read from a stream, you'll need to cache it in a buffer first.

Java NIO ' s buffer oriented approach is slightly different. Data is read to a buffer from which it is later processed. You can move forth and back in the buffer as you need to. This gives is a bit more flexibility during processing. However, you also need to check if the buffer contains all the data for need in order to fully process it. And, you need-to-make sure this when reading more data into the buffer, you don't overwrite data in the buffer with n OT yet processed.

Blocking vs. Non-blocking IO

Java IO ' s various streams is blocking. That means, which when a thread invokes a read () or write (), which thread is blocked until there are some data to read, or th E data is fully written. The thread can do nothing else in the meantime.

Java NIO ' s non-blocking mode enables a thread to request reading data from a channel, and only get what is currently avail Able, or nothing at all, and if no data is currently available. Rather than remain blocked until data becomes available for reading, the thread can go in with something else.

The same is true for non-blocking writing. A thread can request that some data is written to a channel, and not wait for it to be fully written. The thread can then go on and does something else in the mean time.

What threads spend their idle time on if not blocked in IO calls, was usually performing IO on other channels in the mean Time. That's, a single thread can now manage multiple channels of input and output.

Selectors

Java NIO ' s selectors allow a single thread to monitor multiple channels of input. You can register multiple channels with a selector and then use a single thread to "select" the channels that has input Avai lable for processing, or select the channels, is ready for writing. This selector mechanism makes it easy for a single thread to manage multiple channels.

How NIO and IO influences application Design

Whether Choose NIO or IO as your IO toolkit may impact the following aspects of your application design:

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

The API Calls

Of course the API calls when using NIO look different than when using IO. This is no surprise. Rather than just read the data byte for byte from e.g. InputStream A, the data must first is read into a buffer, and then is PR Ocessed from there.

The processing of Data

The processing of the data is also affected when using a pure NIO design vs. an IO design.

In an IO design you read the data byte to byte from an InputStream or a Reader. Imagine were processing a stream of line based textual data. For instance:

1234567890

This stream of text lines could is processed 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 ();  

Notice how the processing was determined by what far the program had executed. In other words, once the first Reader.readline () method returns, you know for sure that a full line of text have been read. The ReadLine () blocks until a full line are read, that's why. You also know, the This line contains the name. Similarly, when the second is ReadLine () call returns, you know that this line contains the age etc.

As you can see, the program progresses only if there is new data to read, and for each step you know. Once the executing thread has progressed past reading a certain piece of data in the code, the thread is not going Backwa RDS in the data (mostly not). This principle are also illustrated in this diagram:

Java io:reading data from a blocking stream.

A NIO implementation would look different. Here is a simplified example:

Bytebuffer buffer = bytebuffer.allocate ($); int bytesread = inchannel.read (buffer);

Notice the second line which reads bytes from the channel into the Bytebuffer. When this method call returns you don ' t know if all the data you need is inside the buffer. All know are that the buffer contains some bytes. This makes processing somewhat harder.

Imagine if, after the first read (buffer), then all of the is read into the buffer is half a line. For instance, "Name:an". Can you process that data? Not really. You need to wait until at LEAs a full line of data have been into the buffer, before it makes sense to process any of the D ATA at all.

So how does know if the buffer contains enough data for it to make sense to be processed? Well, you don ' t. The only-to-find out, is-to-look at the data in the buffer. The result is, which inspect the data in the buffer several times before you know if all the data is Inther E. This is the both inefficient, and can become messy in terms of the program design. For instance:

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

The Bufferfull () method has a keep track of how much data was read into the buffer, and return either Trueor false, depend ing on whether the buffer was full. In other words, if the buffer was ready for processing, it was considered full.

The Bufferfull () method scans through the buffer, but must leave the buffer in the same state as before the Bufferfull () m Ethod was called. If not, the next data read to the buffer might not being read in on the correct location. This isn't impossible, but it's yet another issue to watch out for.

If the buffer is full, it can be processed. If it is isn't full, you might being able to partially process whatever data are there, if that makes sense in your particular C Ase. In many cases it doesn ' t.

The Is-data-in-buffer-ready loop is illustrated in this diagram:

Java nio:reading data from a channel until all needed data are in buffer.

Summary

NIO allows manage multiple channels (network connections or files) using only a single (or few) threads, but the CO St is that parsing the data might was somewhat more complicated than when reading data from a blocking stream.

If you need to manage thousands of open connections simultanously, which all only send a little data, for instance a chat Server, implementing the server in NIO was probably an advantage. Similarly, if you need to keep a lot of open connections to other computers, e.g. in a-peer network, using a single thread To manage all of your outbound connections might is an advantage. This one thread, multiple connections design are illustrated in this diagram:

Java nio:a Single thread managing multiple connections.

If you had fewer connections with very high bandwidth, sending a lot of data at a time, perhaps a classic IO server imple Mentation might is the best fit. This diagram illustrates a classic IO server design:

Java io:a Classic IO server Design-one connection handled by one thread.

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.