NIO improves system performance and nio system performance
In software systems, the I/O speed is much slower than the memory speed. Therefore, I/O is often called the bottleneck of the system. All, improving the I/O speed can greatly improve the integrity of the system.
In java standard I/O, it is implemented based on stream I/O, that is, InputStream and OutPutStream. This stream-based implementation takes byte as the basic unit, it is easy to implement various filters.
NIO and new I/O abbreviation, included in JDK, has the following features:
1. Provide buffer cache support for all original types;
2. Use Charset as the character set encoding and decoding solution;
3. added Channel objects as new original I/O abstractions;
4. file access interfaces supporting lock and memory access to files;
5. Provides Selector-based Asynchronous Network I/O;
NIO is based on blocks. It processes data based on blocks. In NIO, the two most important components are buffer and channel. A buffer is a continuous memory area and a transfer station for reading and writing data from NIO. The channel indicates the source or destination of the buffered data. It is used to read or write data to the buffer and is an interface for accessing the buffer. The relationship between the channel and the buffer
- Buffer class and Channel in NIO
JDK provides a Buffer for each java Native type. Except for ByteBuffer, each Buffer has the same operation, except for the operation type. ByteBuffer can be used for most standard I/O operations.
Channels are used in combination with the Buffer in NIO. A Channel is a two-way Channel that can be read or written. It is a bit similar to Stream, but Stream is unidirectional. The application cannot directly perform read/write operations on the Channel, but must use the Buffer.
The following uses a file copy as an example to briefly introduce the usage of NIO Buffer and Channel. The Code is as follows:
1 public class NioCopyFileTest {2 public static void main (String [] args) throws Exception {3 NioCopyFileTest. copy ("test.txt", "test2.txt"); 4} 5 6 public static void copy (String resource, String destination) throws Exception {7 FileInputStream FCM = new FileInputStream (resource ); 8 FileOutputStream fos = new FileOutputStream (destination); 9 10 FileChannel inputFileChannel = Fi. getChannel (); // Read File Channel 11 FileChannel outputFileChannel = fos. getChannel (); // Write File channel 12 ByteBuffer byteBuffer = ByteBuffer. allocate (1024); // read/write data buffer 13 while (true) {14 byteBuffer. clear (); 15 int length = inputFileChannel. read (byteBuffer); // read data 16 if (length =-1) {17 break; // read completed 18} 19 byteBuffer. flip (); 20 outputFileChannel. write (byteBuffer); // write data 21} 22 inputFileChannel. close (); 23 outputFileChannel. close (); 24} 25}
The comments in the Code are very detailed. The input stream and output stream correspond to a Channel, and the data is read to the buffer through the Read File channel, then write the data to the buffer through the Write File channel. In this way, the file is copied. Note: buffering plays a major role in file transmission, which can alleviate performance differences between memory and hard disk and improve system performance.
- Basic Principles of Buffer
Buffer has three important parameters: position, capacity, and limit ). The meanings of these three parameters are as follows:
The following example illustrates the working principle of Buffer:
1 ByteBuffer buffer = ByteBuffer. allocate (15); // set the buffer size to 15 2 System. out. println ("position:" + buffer. position () + "limit:" + buffer. limit () + "capacity" + buffer. capacity (); 3 for (int I = 0; I <10; I ++) {4 buffer. put (byte) I); 5} 6 System. out. println ("position:" + buffer. position () + "limit:" + buffer. limit () + "capacity" + buffer. capacity (); 7 buffer. flip (); // reset position 8 for (int I = 0; I <5; I ++) {9 System. out. println (buffer. get (); 10} 11 System. out. println ("position:" + buffer. position () + "limit:" + buffer. limit () + "capacity" + buffer. capacity (); 12 buffer. flip (); 13 System. out. println ("position:" + buffer. position () + "limit:" + buffer. limit () + "capacity" + buffer. capacity ());
The above code first allocates a buffer of 15 bytes. In the initial stage, position is 0, capacity is 15, and limit is 15. Note that the position starts from 0, so the position with the index of 15 does not actually exist.
Then add 10 elements to the buffer. position always points to the next position to be placed. All positions are 10, capacity and limit are still 15.
In the flip () operation, the position of the position is reset and the limit is set to the current position. Then, the Buffer enters the Read mode from the write mode, in this way, the read operation can be prevented from reading to a location where no operation is performed. In all cases, the position is 0, the limit is 10, and the capacity is 15.
Then perform five read operations. The read operation sets the position. Therefore, the position is 5, the limit value is 10, and the capacity value is 15.
When performing a flip () operation, you can imagine that position is 0, limit is 5, and capacity is 15.
- Buffer-related operations
Buffer is the most important object in NIO. It also needs to be focused on a series of operations and usage. Here, we will give a brief summary and you can refer to the relevant API for details.
1. Create a Buffer:
There are two common buffer Methods: Use the static method allocate () to allocate a buffer from the heap or create a buffer from an existing array.
1 ByteBuffer buffer = ByteBuffer. allocate (1024); // allocate 2 byte [] arrays = new byte [1024] From the heap; // create 3 ByteBuffer buffer2 = ByteBuffer from the existing array. wrap (arrays );
2. Reset or clear the buffer zone:
Buffer also provides some methods for resetting and clearing the buffer: rewind (), clear (), flip (). Their functions are as follows:
3. read/write buffer:
Read/write operations on Buffer objects are the most important operations of Buffer. buffer provides a Buffer for many read/write operations. For more information, see API.
4. Sign the Buffer Zone
The mark buffer is a useful function in data processing. Like a bookmarkdonefile, it records the current position at any time during data processing and returns to this position at any time, this simplifies or accelerates the data processing process. Related functions include mark () and reset (). Mark () is used to record the current position, and reset () is used to restore to the mark position.
The Code is as follows:
1 ByteBuffer buffer = ByteBuffer. allocate (15); // set the buffer size to 15 2 for (int I = 0; I <10; I ++) {3 buffer. put (byte) I); 4} 5 buffer. flip (); // reset position 6 for (int I = 0; I <buffer. limit (); I ++) {7 System. out. print (buffer. get (); 8 if (I = 4) {9 buffer. mark (); 10 System. out. print ("mark at" + I); 11} 12} 13 System. out. println (); 14 buffer. reset (); 15 while (buffer. hasRemaining () {16 System. out. print (buffer. get (); 17}
Output result:
1 01234mark at4567892 56789
5. Copy the buffer
The replication buffer is based on the original buffer and generates a completely identical buffer. Method: duplicate (). This function is good for processing complex Buffer data. Because the newly generated buffer zone and the metadata buffer zone share the same memory data. In addition, changes made by either party are visible to each other, but both of them maintain their own positions, limit, and capacity. This greatly increases Program Flexibility and makes it possible for multiple parties to process data simultaneously.
The Code is as follows:
1 ByteBuffer buffer = ByteBuffer. allocate (15); // set the buffer size to 15 2 for (int I = 0; I <10; I ++) {3 buffer. put (byte) I); 4} 5 ByteBuffer buffer2 = buffer. duplicate (); // copy the Current Buffer 6 System. out. println ("after buffer duplicate"); 7 System. out. println (buffer); 8 System. out. println (buffer2); 9 buffer2.flip (); 10 System. out. println ("after buffer2 flip"); 11 System. out. println (buffer); 12 System. out. println (buffer2); 13 buffer2.put (byte) 100); 14 System. out. println ("after buffer2 put"); 15 System. out. println (buffer. get (0); 16 System. out. println (buffer2.get (0 ));
The output result is as follows:
1 after buffer duplicate2 java.nio.HeapByteBuffer[pos=10 lim=15 cap=15]3 java.nio.HeapByteBuffer[pos=10 lim=15 cap=15]4 after buffer2 flip5 java.nio.HeapByteBuffer[pos=10 lim=15 cap=15]6 java.nio.HeapByteBuffer[pos=0 lim=10 cap=15]7 after buffer2 put8 1009 100
6. Buffer shard
The slice () method is used for buffer sharding. It creates a new sub-buffer for the existing buffer, and shares data between the sub-buffer and the parent buffer. The sub-buffer has a complete buffer model structure. When processing a buffer segment, you can use a slice () method to obtain a sub-buffer, and then process the sub-buffer like a normal buffer without considering the boundary issue, this facilitates system modularization.
1 ByteBuffer buffer = ByteBuffer. allocate (15); // set the buffer size to 15 2 for (int I = 0; I <10; I ++) {3 buffer. put (byte) I); 4} 5 buffer. position (2); 6 buffer. limit (6); 7 ByteBuffer subBuffer = buffer. slice (); // copy the buffer 8 for (int I = 0; I <subBuffer. limit (); I ++) {9 byte B = subBuffer. get (I); 10 B = (byte) (B * 10); 11 subBuffer. put (I, B); 12} 13 buffer. limit (buffer. capacity (); 14 buffer. position (0); 15 for (int I = 0; I <buffer. limit (); I ++) {16 System. out. print (buffer. get (I) + ""); 17}
Output result:
1 0 1 20 30 40 50 6 7 8 9 0 0 0 0 0
7. Read-Only Buffer
You can use the asReadOnlyBuffer () method of the buffer object to obtain a read-only buffer that is consistent with the current buffer and shares memory data. The read-only buffer is very useful for data security. The read-only buffer can ensure that the data is not modified. At the same time, the read-only buffer and the original buffer are shared with the memory block. Therefore, the modification to the original buffer is also visible.
The Code is as follows:
1 ByteBuffer buffer = ByteBuffer. allocate (15); // set the buffer size to 15 2 for (int I = 0; I <10; I ++) {3 buffer. put (byte) I); 4} 5 ByteBuffer readBuffer = buffer. asReadOnlyBuffer (); 6 for (int I = 0; I <readBuffer. limit (); I ++) {7 System. out. print (readBuffer. get (I) + ""); 8} 9 System. out. println (); 10 buffer. put (2, (byte) 20); 11 for (int I = 0; I <readBuffer. limit (); I ++) {12 System. out. print (readBuffer. get (I) + ""); 13}
Result:
1 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 2 0 1 20 3 4 5 6 7 8 9 0 0 0 0 0
It can be seen that the read-only buffer is not a snapshot of the original buffer at a certain time point, but shares memory data with the original buffer. When the read-only buffer is modified, the ReadOnlyBufferException is reported.
8. File ing to memory:
NIO provides a method to map files to memory for I/O operations, which can be much faster than conventional stream-based I/O operations. This operation is mainly implemented by the FileChannel. map () method.
Use File ing to map text files to the memory through FileChannel. Then read the file content in the memory. You can also modify the Buffer to write the actual data to the corresponding hard disk.
1 RandomAccessFile raf = new RandomAccessFile ("D: \ test.txt", "rw"); 2 FileChannel fc = raf. getChannel (); 3 MappedByteBuffer mbf = fc. map (MapMode. READ_WRITE, 0, raf. length (); // map the file to memory 4 while (mbf. hasRemaining () {5 System. out. println (mbf. get (); 6} 7 mbf. put (0, (byte) 98); // modify the file 8 raf. close ();
9. process structured data
NIO also provides methods for processing structured data, called scattering and clustering. Scattering is to read a group of data into a group of buffer, and aggregation is to write data into a group of buffer. The basic usage of aggregation and scattering is similar to that of a single buffer operation. This group of buffers is similar to a large buffer.
Scattering/clustering IO is very useful for processing structured data. For example, for reading and writing a file with a fixed format, you can construct several buffer entries that conform to the file structure when the specific structure of the file is known, make the buffer size exactly match the size of each segment of the file.
For example, you can create a file named "Name: Zhang San, age: 18" by clustering, and then parse the file by scattering.
1 ByteBuffer nameBuffer = ByteBuffer. wrap ("Name: James ,". getBytes ("UTF-8"); 2 ByteBuffer ageBuffer = ByteBuffer. wrap ("Age: 18 ". getBytes ("UTF-8"); 3 int nameLength = nameBuffer. limit (); 4 int ageLength = ageBuffer. limit (); 5 ByteBuffer [] bufs = new ByteBuffer [] {nameBuffer, ageBuffer}; 6 File file File = new File ("D: \ name.txt"); 7 if (! File. exists () {8 file. createNewFile (); 9} 10 FileOutputStream fos = new FileOutputStream (file); 11 FileChannel channel = fos. getChannel (); 12 channel. write (bufs); 13 channel. close (); 14 15 ByteBuffer nameBuffer2 = ByteBuffer. allocate (nameLength); 16 ByteBuffer ageBuffer2 = ByteBuffer. allocate (ageLength); 17 ByteBuffer [] bufs2 = new ByteBuffer [] {nameBuffer2, ageBuffer2}; 18 FileInputStream FD = new FileInputStream ("D :\\ name.txt "); 19 FileChannel channel2 = fiis. getChannel (); 20 channel2.read (bufs2); 21 String name = new String (bufs2 [0]. array (), "UTF-8"); 22 String age = new String (bufs2 [1]. array (), "UTF-8"); 23 24 System. out. println (name + age );
The combination with the channel simplifies the difficulty of the Buffer for structured data processing.
Note that ByteBuffer reads files into the memory at a time for processing, while the Stream mode reads files while processing data, which is also the main reason for the performance difference between the two.
NIO Buffer also provides a class that can directly access the system's physical memory-DirectBuffer. The normal ByteBuffer still allocates space on the JVM heap, and its maximum memory is limited by the maximum heap. DirecBuffer is directly allocated to physical memory and does not occupy heap space. The method for creating DirectBuffer is ByteBuffer. allocateDirect (capacity ).
When accessing a common ByteBuffer, the system always uses a "kernel buffer" for indirect operations. The location of ByteBuffer is equivalent to the "kernel buffer ". Therefore, DirecBuffer is an operation closer to the underlying layer.
The access speed of DirectBuffer is much higher than that of ByteBuffer, but the time consumed for its creation and destruction is much greater than that of ByteBuffer. It is obviously not suitable for the use of DirectBuffer when Buffer needs to be created and destroyed frequently. However, if the DirectBuffer can be reused, it can greatly improve the system performance.