This article from: http://www.iteye.com/topic/834447
1.BasicConcept
Io is the process of copying data from the primary storage and external devices (hard disks, terminals, and networks. Io is the underlying function implementation of the operating system, which is completed by I/O commands.
The system provides advanced tools for executing I/O in all languages. (C's printf scanf, Java's object-oriented encapsulation)
2. java standard Io Review
Java standard Io class library is an abstraction of Io object-oriented. Based on the underlying implementation of local methods, we do not need to pay attention to the underlying implementation. Inputstream \ outputstream (byte stream): one byte is transferred at a time. Reader \ writer (Bytes stream): one character at a time.
3. Nio Introduction
NIO is short for Java new Io, a new API provided in jdk1.4. Sun officially advertised the following features:
-Buffer caching is supported for all original types.
-Character set encoding and decoding solution.
-Channel: A new original I/O abstraction.
-Supports file access interfaces for lock and memory ing files.
-Provides non-bloking non-blocking high-scalability network I/O.
This article will learn and introduce these features.
4. Buffer & Chanel
Channel and buffer are two of the most basic data types abstract.
Buffer:
-It is a continuous memory block.
-It is the primary location for reading or writing NiO data.
Channel:
-Data Source or data destination
-This interface is used to provide data to the buffer or to read the buffer data. It is the unique interface of the buffer object.
-Asynchronous I/O support
Figure 1: Channel-buffer relationship
Example 1: copyfile. Java:
Package COM. zxiaoyao. io; import Java. io. fileinputstream; import Java. io. filenotfoundexception; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. NIO. bytebuffer; import Java. NIO. channels. filechannel; public class nioforcopyfile {public static void main (string [] ARGs) {string infile = "D:/copy. SQL "; string OUTFILE =" D:/copy.txt "; // obtain the input/output stream fileinputstream fin of the source and target files; try {fin = new fileinputstream (infile ); fileoutputstream fout = new fileoutputstream (OUTFILE); // gets the input/output channel filechannel Fcin = fin. getchannel (); filechannel fcout = fout. getchannel (); // create a buffer bytebuffer buffer = bytebuffer. allocate (1024); While (true) {// clear method to reset the buffer, which can be read into the buffer. clear (); int r = Fcin. read (buffer); If (r =-1) {break;} // The flip method allows the buffer to write newly written data to another buffer channel. flip (); // writes data to the buffer fcout from the input channel. write (buffer) ;}} catch (filenotfoundexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}
The internal structure of buffer is as follows (copying data ):
Figure 2: Buffer Internal Structure
A buffer consists of three variables: Position, limit, and capacity to control the read/write process. The meanings of the three variables are shown in the following table:
|
Parameters |
Write mode |
Read mode |
|
Position |
The number of data units currently written. |
The location of the currently read unit data. |
|
Limit |
The maximum number of units of data that can be written is the same as the capacity. |
The maximum number of units of data that can be read, which is consistent with the unit of data previously written. |
|
Capacity |
Buffer Capacity |
Buffer Capacity |
Common buffer methods:
Flip (): converts the write mode to the Read mode.
Rewind (): resets position to 0, which is generally used for repeated read.
Clear (): clears the buffer and prepares to be written again (position is changed to 0, and limit is changed to capacity ).
Compact (): Copy unread data to the buffer header.
Mark (), reset (): Mark can mark a position, and reset can be reset to this position.
Common buffer types: bytebuffer, mappedbytebuffer, charbuffer, doublebuffer, floatbuffer, intbuffer, longbuffer, and Protocol buffer.
Common Channel types: filechannel, datagramchannel (UDP), socketchannel (TCP), and serversocketchannel (TCP)
A simple performance test was conducted on the local machine. My laptop has average performance. (For specific code, see the attachment. See the NIO. sample. filecopy Package example.) The following is the reference data:
-Scenario 1: Copy A 370m File
-Scenario 2: three threads copy at the same time. Each thread copies a 370m file.
|
Scenario |
Fileinputstream +
Fileoutputstream |
Fileinputstream +
Bufferedinputstream +
Fileoutputstream |
Bytebuffer +
Filechannel |
Mappedbytebuffer
+ Filechannel |
|
Scenario time (MS) |
25155 |
17500 |
19000 |
16500 |
|
Scenario 2 time (MS) |
69000 |
67031 |
74031 |
71016 |
5. NiO. charset
Character encoding and decoding: the bytecode itself is only a number and is correctly parsed in the correct context. When storing data to bytebuffer, you must consider the encoding method of the character set. Reading and displaying bytebuffer data involves decoding the character set.
Java. NiO. charset provides a solution for encoding and decoding.
Taking the most common HTTP request as an example, the request must be correctly encoded. The response must be correctly decoded when the response is received.
The following code sends a request to Baidu and obtains the result for display. The example demonstrates the use of charset.
Example 2 baidureader. Java
package com.zxiaoyao.io;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.SocketChannel;import java.nio.charset.Charset;public class BaiduReader {private Charset charset = Charset.forName("GBK");private SocketChannel channel;public void readerHtml(){InetSocketAddress socketAddress = new InetSocketAddress("www.baidu.com",80);try {channel = SocketChannel.open(socketAddress);channel.write(charset.encode("GET "+"/ HTTP/1.1"+"\r\n\r\n"));ByteBuffer buffer = ByteBuffer.allocate(1024);while(channel.read(buffer)!= -1){buffer.flip();System.out.println(charset.decode(buffer));buffer.clear();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void main(String[] args) {new BaiduReader().readerHtml();}}
6. Non-blocking Io
Non-blocking Io will be understood in terms of blocking, non-blocking, non-blocking principle, and asynchronous core API.
What is blocking?
A common network Io communication process is as follows:
Figure 3: basic network communication process
From the network communication process, we can understand what is blocking:
If the connection has not arrived in the above process, the accept will be blocked, the program runs here and has to be suspended, and the CPU will execute other threads.
In the above process, if the data is not ready, the read operation will also block.
Block network I/O features: multi-threaded processing of multiple connections. Each thread has its own stack space and consumes some CPU time. Every thread will be blocked when it is ready externally. Blocking results in a large number of context switches. In addition, context switching of most processes may be meaningless. For example, if a thread listens to a port and requests only come in several times a day, but the CPU has to continuously perform context switching attempts for the thread, most of the switches end with blocking.
What is non-blocking?
The following is a metaphor:
A bus from A to B may get off at many points on the road. The driver does not know which persons will get off the bus. What should they do better?
1. The driver regularly asks if each passenger has arrived at the destination. If someone says so, the driver stops and gets off the bus. (Similar to blocking)
2. Each person tells the conductor his destination and goes to bed. The driver only interacts with the conductor. At a certain point, the conductor notifies the passengers to get off the bus. (Similar to non-blocking)
Obviously, each person who wants to reach a destination can be considered as a thread, and the driver can think of it as a CPU. In the blocking mode, each thread needs to continuously poll and switch the context to locate the destination. In the non-blocking mode, every passenger (thread) is sleeping (sleep) and wakes up only when the real external environment is ready. Such a wake-up will certainly not be blocked.
Principle of non-blocking
Switch the entire process to a small task and complete it through collaboration between tasks.
A dedicated thread is used to process all Io events and distribute them.
Event-driven mechanism: triggered when an event arrives, rather than synchronously monitoring the event.
Thread communication: threads communicate with each other through wait, notify, and other methods. Make sure that each context switch is meaningful. Reduce Unnecessary process switching.
The following is the structure of asynchronous IO:
Figure 4: Basic Principle of non-blocking
Reactor is the predicate of the conductor. The processing process of each thread is generally to read data, decode, compute, encode, and send responses.
Asynchronous Io core API
Selector
Core class of asynchronous Io, which can detect events on one or more channels and distribute events.
You can use a select thread to listen to events on multiple channels and trigger corresponding responses based on event drivers. Instead of allocating a thread to each channel.
Selectionkey
It contains the event status information and the binding of the channel corresponding to the time.
Example 1 a single thread listens to two ports. (See the NIO. Asyn Package example .)
Example 2 NiO thread Collaboration achieves reasonable resource utilization. (Wait, notify ). (See the example in NIO. Asyn. Multithread)