Java NIO: NIO overview, javanio Overview

Source: Internet
Author: User

Java NIO: NIO overview, javanio Overview

Java NIO: NIO Overview

I talked about several IO models in the previous blog. Now we start to enter the Java NIO programming topic. NIO is a new API provided in Java 4 to solve traditional IO problems. This article introduces several basic concepts of Java NIO.

The following is the directory outline of this article:

I. Several Basic Concepts in NIO

Ii. Channel

Iii. Buffer

4. Selector

If there are any mistakes, please forgive me and welcome criticism and correction.

Please respect the author's Labor achievements, and repost the original text link:

Http://www.cnblogs.com/dolphin0520/p/3919162.html

I. Several Basic Concepts in NIO

There are several key concepts in NIO: Channel, Buffer, and Selector ).

First of all, let's start with the Channel. As the name suggests, it is the path to something that provides a Channel for a certain party. In traditional IO, we want to read the content of a file, which is usually read as follows:

123456789 public class Test {    public static void main(String[] args) throws IOException  {        File file = new File("data.txt");        InputStream inputStream = new FileInputStream(file);        byte[] bytes = new byte[1024];        inputStream.read(bytes);        inputStream.close();    }  }

Here, InputStream actually provides a channel for reading files.

Therefore, we can compare the Channel in nio with the Stream in traditional IO. However, in traditional IO, Stream is unidirectional. For example, InputStream can only perform read operations, while OutputStream can only perform write operations. The Channel can be used for both read and write operations.

Buffer is a very important thing in NIO. In NIO, all data reading and writing are inseparable from Buffer. For example, in the code above, the read data is placed in the byte array, while in NIO, the read data can only be placed in Buffer. Similarly, data is written to the Buffer first.

The following describes one of the most important aspects of NIO: Selector. It can be said that it is the most critical part of NIO. Selector is used to poll every registered Channel. Once a registered event occurs in the Channel, the event is obtained and processed.

For example, let's look at the example below:

Use a single thread to process a Selector, and then use the Selector. select () method to obtain the arrival event. After obtaining the arrival event, you can respond to these events one by one.

Ii. Channel

As mentioned above, the Channel is very similar to the Stream in traditional IO. Although it is very similar, there is a big difference, the main difference is: the Channel is bidirectional, through a Channel can both read and write; and Stream can only perform one-way operations, only one Stream can be read or written;

The following channels are commonly used:

  • FileChannel
  • SocketChanel
  • ServerSocketChannel
  • DatagramChannel

You can use FileChannel to read data from or write data to a file, use SocketChannel to read and write data to both ends of the network connection, and use ServerSocketChanel to listen to TCP connections initiated by the client, create a new SocketChannel for each TCP connection to read and write data. Use the mongoramchannel to read and write data to both ends of the network connection using UDP protocol.

The following example shows how to write data to a file through FileChannel:

1234567891011121314 public class Test {    public static void main(String[] args) throws IOException  {        File file = new File("data.txt");        FileOutputStream outputStream = new FileOutputStream(file);        FileChannel channel = outputStream.getChannel();        ByteBuffer buffer = ByteBuffer.allocate(1024);        String string = "java nio";        buffer.put(string.getBytes());        buffer.flip();     // The flip method of buffer must be called here        channel.write(buffer);        channel.close();        outputStream.close();    }  }

A program that passes through the Protocol will write the string "java nio" to the data.txt file under the project directory. Note that the buffer flip method must be called before calling the channel write method; otherwise, the content cannot be correctly written, as for the specific reasons, we will elaborate on the usage of Buffer in the next blog.

Iii. Buffer

Buffer is actually a container and a continuous array. The Channel provides a Channel for reading data from files and networks, but the data read or written must be transmitted through the Buffer. Take a look at the figure below to understand:

The figure above describes the process of sending data from a client to the server and then receiving data from the server. When sending data, the client must first store the data in the Buffer and then write the content in the Buffer to the channel. The server side must read data into the Buffer through the Channel, and then retrieve the data from the Buffer for processing.

In NIO, Buffer is a top-level parent class, which is an abstract class. The common Buffer subclasses include:

  • ByteBuffer
  • IntBuffer
  • CharBuffer
  • LongBuffer
  • DoubleBuffer
  • FloatBuffer
  • Protocol Buffer

For file read/write, the above Buffer may be used. However, for network read/write, the most used is ByteBuffer.

The usage of Buffer and its limit, posiion, and capacity attributes are described in the next article.

4. Selector

The Selector class is the core class of NIO. Selector can detect events on multiple registered channels. If an event occurs, it obtains the event and responds to each event. In this way, you can manage multiple channels by using a single thread, that is, managing multiple connections. In this way, the function is called only when a read/write event occurs in the connection, which greatly reduces the system overhead and eliminates the need to create a thread for each connection, you do not need to maintain multiple threads and avoid overhead caused by context switching between multiple threads.

A key class related to Selector is SelectionKey. A SelectionKey represents an event that arrives. These two classes constitute the key logic for the server to process the business.

The usage of the Selector class will be described in subsequent articles.

References:

Http://blog.csdn.net/wuxianglong/article/details/6604817

Http://www.360doc.com/content/12/0515/11/1542811_211144310.shtml

Http://www.iteye.com/topic/834447

Http://weixiaolu.iteye.com/blog/1479656

Http://ifeve.com/overview/

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.