JAVA NIO Memory Mapping (reprint)

Source: Internet
Author: User

Original address: http://blog.csdn.net/fcbayernmunchen/article/details/8635427

A new feature of the NIO package in the Java class Library is a memory-mapped file relative to the IO package, which is not often used in daily programming, but is an ideal way to improve efficiency when dealing with large files. In this article I would like to combine the operating system (OS) related knowledge to introduce the principle.

In traditional file IO operations, we are invoking the underlying standard IO system call function read (), write (), which is provided by the operating system, at which point the process calling this function (in Java, the Java process) is switched from the current user state to the kernel state. Then the kernel code of the OS is responsible for reading the corresponding file data into the kernel's IO buffer and then copying the data from the kernel IO buffer to the private address space of the process, thus completing an IO operation. And why should superfluous get a kernel io buffer to make 2 copies of the data when it was just a single copy of the data? I want to learn the operating system or computer system structure of the people know that this is to reduce the disk IO operation, in order to improve performance and consider, because our program access is generally with local, that is, the so-called local principle, here is mainly refers to the spatial locality, that is, we have access to the file of a certain piece of data, Then it is likely that the next piece of data will be accessed, because the disk IO operation is slower than direct access to memory several orders of magnitude, so the OS based on the local principle will be in a read () system call in the process of pre-reading more file data cached in the kernel IO buffer, When continuing to access the file data in the buffer, it copies the data directly to the process private space, avoiding the inefficient disk IO operation again. In Java, when we take the file operation flow under the IO package, such as:

[Java] View plain copy

FileInputStream in = new FileInputStream ("D:\\java.txt");

[Java] View plain copy

In.read ();

Inside the Java virtual machine, the underlying read () system call to the OS is called to complete, as described above, when the second call to In.read () is likely to return data directly from the kernel buffer (there may also be a transit through the native heap, because these functions are declared as native , that is, local platform-related, so there may be a relay in C code, such as Win32 in C code from the OS to read data, and then passed to the JVM memory). That being the case, why should Java's IO package provide a Bufferedinputstream class as a buffer? The key is four characters, "System call"! When the OS kernel buffer data is read, a system call operation (via native C function call) is initiated, and the cost of the system call is relatively high, involving a series of operations such as context switching of the process user state and kernel state, so we often use the following packaging:

[Java] View plain copy

FileInputStream in = new FileInputStream ("D:\\java.txt");

[Java] View plain copy

Bufferedinputstream buf_in = new Bufferedinputstream (in);

[Java] View plain copy

Buf_in.read ();

In this way, every time we buf_in.read (), Bufferedinputstream automatically reads more bytes of data into one of its own internal byte array buffers, as appropriate, so that we can reduce the number of system calls, Thus achieving the purpose of its buffer. So it is clear that Bufferedinputstream's role is not to reduce the number of disk IO operations (which the OS has done for us), but to improve performance by reducing the number of system calls. Similarly Bufferedouputstream, Bufferedreader/writer is the same. There are similar implementations in the C-language library, such as Fread (), which is the buffered IO in the C language, with the same function as Bufferedinputstream ().

Here simple reference under JDK6 in the Bufferedinputstream source code verification:

[Java] View plain copy

Public

Class Bufferedinputstream extends FilterInputStream {

private static int defaultbuffersize = 8192;

/**

* The internal buffer array where the data is stored. When necessary,

* It may is replaced by another array of

* A different size.

*/

Protected volatile byte buf[];

/**

* The index one greater than the last valid byte in

* The buffer.

* This value was always

* In the range <code>0</code> through <code>buf.length</code>;

* Elements <code>buf[0]</code> through <code>buf[count-1]

* </code>contain buffered input data obtained

* from the underlying input stream.

*/

protected int count;

/**

* The current position in the buffer. This is the index of the next

* character to is read from the <code>buf</code> array.

* <p>

* This value was always in the range <code>0</code>

* through <code>count</code>. If It is less

* than <code>count</code>, then <code>buf[pos]</code>

* is the next byte to be supplied as input;

* If it is equal to <code>count</code>

* The next <code>read</code> or <code>skip</code>

* Operation'll require more bytes

* Read from the contained input stream.

*

* @see Java.io.bufferedinputstream#buf

*/

protected int pos;

/* Omitted here to N multiple code------>> */

/**

* See

* The general contract of the <code>read</code>

* Method of <code>inputstream</code>.

*

* @return The next byte of data, or <code>-1</code> if the end of the

* Stream is reached.

* @exception IOException If this input stream have been closed by

* Invoking its {@link #close ()} method,

* or an I/O error occurs.

* @see Java.io.filterinputstream#in

*/

public synchronized int read () throws IOException {

if (POS >= count) {

Fill ();

if (POS >= count)

return-1;

}

return Getbufifopen () [pos++] & 0xFF;

}

As we can see, Bufferedinputstream internally maintains a byte array byte[] buf to implement the function of the buffer, and the Buf_in.read () method that we call has an if judgment before returning the data, if the current index of the BUF array is not in a valid cable Within the range, that is, if condition is established, buf field maintenance buffer is not enough, this time will call the internal fill () method to fill, and fill () will read more data into the BUF array buffer, and then return the current byte data, if the IF condition is not set directly from the BUF buffer The area array returns data. where Getbufifopen () returns a reference to the BUF field. By the way, the BUF field in the source is declared as protected volatile byte buf[]; The main purpose is to guarantee the memory visibility of the BUF array in a multithreaded concurrency environment with the volatile keyword.

The memory-mapped parts of Java NIO say so much, primarily to pave the way for a knowledge system to better understand the benefits of memory-mapped files.

The biggest difference between a memory-mapped file and a previously mentioned standard IO operation is that it eventually reads the data from the disk, but it does not need to read the data to the OS kernel buffer, but rather directly maps a portion of the process's user private address space to the file object, as if it were read directly from memory , write a file, the speed of course is fast. To clarify this, we take the Linux operating system as an example, see:

This figure is the process virtual memory in Linux 2.X, that is, the virtual address space of the process, if your machine is 32 bits, then there is a virtual address space of 2^32 = 4G, we can see an area in the graph: "Memory mapped region for shared Libr Aries ", this area is the memory map file in the time of a certain part of the virtual address and the file object to establish a mapping relationship, when the data is not copied into memory, but when the process Code first reference to the virtual address within this code, triggered a page fault, The OS copies the relevant part of the file directly into the user's private space of the process according to the mapping relation, and repeats the OS page Scheduler operation when the nth page data is manipulated. Note that the main reason why the memory-mapped file is more efficient than standard IO is that it is less likely to copy the data to the OS kernel buffer (which may be less of a step in the native heap transfer).

3 Memory mapping modes are available in Java: Read-only (readonly), read-write (Read_write), Private (private), and for read-only mode, a Readonlybufferexception exception is thrown if the program attempts to write. The second mode of reading and writing indicates that writing or modifying the contents of a file by means of a memory-mapped file is immediately reflected in the disk file, and other processes that share the same mapping file will see changes immediately! Instead of each process having its own kernel buffers like the standard IO, such as Java code, without the flush () or close () operation of the IO output stream, modifications to the file are not updated to disk unless the process runs out, and the last dedicated mode uses the OS's "copy-on-write" Principle, that is, in the absence of write operations, multiple processes are the same piece of physical memory of shared files (the virtual address of the process points to the same physical address), once a process is written, the affected file data will be copied to the private buffer of the process, Will not be reflected in the physical file.

In Java NiO it is easy to create a memory-mapped area with the following code:

File File = new file ("E:\\download\\office2007pro.chs.iso");

FileInputStream in = new FileInputStream (file);

FileChannel channel = In.getchannel ();

Mappedbytebuffer buff = Channel.map (FileChannel.MapMode.READ_ONLY, 0,channel.size ());

Here we create a read-only memory-mapped file area, and then I'm going to test the performance benefits compared to the channel operations in ordinary NiO, first look at the following code:

public class Iotest {

static final int buffer_size = 1024;

public static void Main (string[] args) throws Exception {

File File = new file ("F:\\aa.pdf");

FileInputStream in = new FileInputStream (file);

FileChannel channel = In.getchannel ();

Mappedbytebuffer buff = channel.map (FileChannel.MapMode.READ_ONLY, 0,

Channel.size ());

Byte[] B = new byte[1024];

int len = (int) file.length ();

Long begin = System.currenttimemillis ();

for (int offset = 0; offset < len; offset + = 1024) {

if (Len-offset > Buffer_size) {

Buff.get (b);

} else {

Buff.get (new Byte[len-offset]);

}

}

Long end = System.currenttimemillis ();

System.out.println ("Time is:" + (End-begin));

}

}

The output is 63, that is, it takes only 78 milliseconds to read a 86M file through a memory-mapped file, and I am now looking at the channel operation for ordinary NiO:

File File = new file ("F:\\liq.pdf");

FileInputStream in = new FileInputStream (file);

FileChannel channel = In.getchannel ();

Bytebuffer buff = bytebuffer.allocate (1024);

Long begin = System.currenttimemillis ();

while (Channel.read (buff)! =-1) {

Buff.flip ();

Buff.clear ();

}

Long end = System.currenttimemillis ();

System.out.println ("Time is:" + (End-begin));

The output is 468 milliseconds, almost 6 times times the gap, the larger the file, the greater the gap. Therefore, the memory map file is particularly suitable for large file operations, Java limit is not more than Integer.max_value, that is, about 2G, but we can use the Sub-mapping file (CHANNEL.MAP) different parts to achieve the purpose of operating the entire file.

According to the official JDK documentation, the memory-mapped file belongs to a direct buffer in the JVM and can also be created by Bytebuffer.allocatedirect (), or directmemory, as a direct buffer. They are less the data copy overhead of the intermediate buffers than the underlying IO operations. They are also part of the JVM's out-of-heap memory and are not constrained by the JVM heap memory size.

Where the default size of Directmemory is equivalent to the JVM maximum heap, theoretically limited by the virtual address space size of the process, such as 32-bit Windows, each process has 4G of virtual space to remove 2G for OS kernel retention, and then subtract the JVM heap maximum value, The remaining is the directmemory size. By setting the JVM parameter-xmx64m, which is the JVM maximum heap of 64M, then execute the following procedure to prove that the directmemory is not controlled by the JVM heap size:

[Java] View plain copy

public static void Main (string[] args) {

Bytebuffer.allocatedirect (1024*1024*100); 100MB

}

We set the JVM heap 64M limit, and then allocate 100MB space on the direct memory, the program executes directly error: Exception in thread "main" Java.lang.OutOfMemoryError:Direct buffer Memory Then I set the-xmx200m, the program ends normally. Then I modify the configuration:-xmx64m-xx:maxdirectmemorysize=200m, the program ends normally. It is therefore concluded that the size of the direct memory directmemory defaults to the maximum value of the JVM heap of-xmx, but is not limited by it, but is controlled separately by the JVM parameter maxdirectmemorysize. Next, we prove that direct memory is not allocated to the JVM heap. We first execute the following program and set the JVM parameter-XX:+PRINTGC,

public static void Main (string[] args) {

for (int i=0;i<20000;i++) {

Bytebuffer.allocatedirect (1024*100); 100K

}

}

The output results are as follows:

[GC 1371k->1328k (61312K), 0.0070033 secs]

[Full GC 1328k->1297k (61312K), 0.0329592 secs]

[GC 3029k->2481k (61312K), 0.0037401 secs]

[Full GC 2481k->2435k (61312K), 0.0102255 secs]

We see fewer GC executions, but triggered two full GC, because direct memory is not affected by GC (the new generation of minor GC), and it is only possible to reclaim direct memory when the full GC of the old age is executed! Direct memory is referenced by Directbytebuffer objects stored in the JVM heap, so the full GC is triggered when numerous directbytebuffer objects are fed into the old age from the Cenozoic.

Let's look at the allocation of memory areas directly on the JVM heap:

[Java] View plain copy

public static void Main (string[] args) {

R (int i=0;i<10000;i++) {

Bytebuffer.allocate (1024*100); 100K

}

Bytebuffer.allocate means allocating memory directly on the JVM heap, so affected by the new generation of Minor GC, the output is as follows:

[GC 16023k->224k (61312K), 0.0012432 secs]

[GC 16211k->192k (77376K), 0.0006917 secs]

[GC 32242k->176k (77376K), 0.0010613 secs]

[GC 32225k->224k (109504K), 0.0005539 secs]

[GC 64423k->192k (109504K), 0.0006151 secs]

[GC 64376k->192k (171392K), 0.0004968 secs]

[GC 128646k->204k (171392K), 0.0007423 secs]

[GC 128646k->204k (299968K), 0.0002067 secs]

[GC 257190k->204k (299968K), 0.0003862 secs]

[GC 257193k->204k (287680K), 0.0001718 secs]

[GC 245103k->204k (276480K), 0.0001994 secs]

[GC 233662k->204k (265344K), 0.0001828 secs]

[GC 222782k->172k (255232K), 0.0001998 secs]

[GC 212374k->172k (245120K), 0.0002217 secs]

As you can see, because the memory is allocated directly on the JVM heap, multiple GC is triggered and the full GC is not touched because the object has no chance to enter the old age.

I would like to raise the question that the directmemory in NiO and the memory file mappings belong to the direct buffer, but the former is related to-xmx and-xx:maxdirectmemorysize, and the latter has no JVM parameters to affect and control, This makes me wonder if the direct buffers are the same, which refers to the native heap in the Java process, which involves the DLL portion of the underlying platform, such as Win32, because the memory allocated by malloc (in C) belongs to the native heap, not the JVM heap, This is also why directmemory can significantly improve performance in some scenarios, because it avoids the duplication of data between the native heap and the JVM heap, while the latter is not native heap and is created directly by the Java process An association mapping between a virtual address space and a file object, see the "Memory mapped region for shared libraries" area in the Linux virtual memory graph, so that the area of the memory-mapped file is not within the scope of the JVM GC's collection, Because it does not belong to the heap area itself, unloading this part of the area can only be implemented by system call Unmap (), while the JAVA API provides only the Filechannel.map form of the memory-mapped area, but does not provide the corresponding unmap (), which is very confusing, Cause to unload this part of the area is more troublesome.

Finally, try using directmemory to manipulate the previous memory mapping and basic channel operations, to see how the program performs in direct memory operations:

File File = new file ("F:\\liq.pdf");

FileInputStream in = new FileInputStream (file);

FileChannel channel = In.getchannel ();

Bytebuffer buff = bytebuffer.allocatedirect (1024);

Long begin = System.currenttimemillis ();

while (Channel.read (buff)! =-1) {

Buff.flip ();

Buff.clear ();

}

Long end = System.currenttimemillis ();

System.out.println ("Time is:" + (End-begin));

The program output is 312 milliseconds, it appears to be faster than the normal NIO channel operation (468 milliseconds), but there is too much difference in the 63 second than the MMAP memory map, I think it should not be, through modification; Bytebuffer buff = bytebuffer.allocatedirect (1024); is Bytebuffer buff = bytebuffer.allocatedirect ((int) file.length ()), which is a one-time allocation of the entire file length of out-of-heap memory, with a final output of 78 milliseconds, Thus, two conclusions can be drawn: 1. The allocation of out-of-heap memory is time-consuming. 2. or more than the mmap memory mapping comes slow, do not say that through the mmap read the data is also involved in page faults, paging system calls, it seems that the memory map file really NB Ah, this is just 86M files, if the G The size of it?

The last point is that directmemory memory is recycled only when the JVM executes the full GC, so if you allocate too much memory space on it, the OutOfMemoryError will also appear, even if much of the memory in the JVM heap is idle.

I would like to add an additional knowledge point, about the JVM heap size is not limited to physical memory, but is limited to the virtual memory space size, in theory, the virtual address space of the process, but in fact, our virtual memory space is limited, the general Windows on the default on the C drive, The size is about twice times the physical memory. I made an experiment: my machine is a 64-bit win7, then in theory, the process virtual space is almost infinite, physical memory is 4G, and I set-xms5000m, that is, when starting a Java program, one-time application to more than the physical memory size of 5000M memory, the program starts normally, and when I add to- xms8000m in the time of the Oom error, and then I modified the increase Win7 virtual memory, the program started normally, indicating that-XMS limited by the size of virtual memory. I set up-xms5000m, which exceeds 4G of physical memory and constantly creates objects in a dead loop and guarantees that it will not be recycled by GC. Program run after a while the whole computer almost freezes, that is stuck, reflect very slow very slow, speculation is a system bump, that is, frequent page scheduling displacement caused,-xms-xmx is not limited to the size of physical memory, but integrated virtual memory, the JVM will be based on the computer virtual memory settings to control.

JAVA NIO Memory Mapping (reprint)

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.