Java NIO Memory Map---g large file processing

Source: Internet
Author: User

Lin Bingwen Evankaka original works. Reprint please specify the source Http://blog.csdn.net/evankaka

Absrtact: This paper mainly discusses the principle and process of memory mapping in Java, compares with the traditional IO, and finally, illustrates the result with an example.

What is memory-mapped IO and memory-mapped files in Java?
The memory-mapped file is very special, it allows the Java program to read the contents of the file directly from memory, by mapping the whole or part of the file to memory, the operating system handles the load request and writes the file, the application only needs to deal with memory, which makes the IO operation very fast. The memory used to load the memory-mapped file is outside the Java heap.     The Java programming language supports memory-mapped files, which can be read and written directly from memory through Java.nio packages and mappedbytebuffer.

Memory-Mapped files

A memory-mapped file that is mapped by a file into a piece of memory. Win32 provides a function that allows an application to map files to a process (createfilemapping). Memory-mapped files are somewhat similar to virtual memory, where a memory-mapped file preserves an area of an address space, while the physical memory is submitted to this zone, and the physical memory of the memory-file mapping comes from a file that already exists on disk, and the file must be mapped first before it can be manipulated. When you use a memory-mapped file to process files stored on disk, you will no longer have to perform I/O operations on the files, making the memory-mapped files a significant part of processing large data volumes.

Memory-Mapped IO

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. This is to reduce the disk IO operation, in order to improve the performance of the consideration, 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 to continue to access the next piece of data, Because disk IO operations are more than a few orders of magnitude slower than direct access memory, the OS will read more file data in the kernel IO buffer during a read () system call, and then copy the data directly into the process private space when the file data continues to be accessed in the buffer, based on the locality principle. Avoids a second inefficient disk IO operation. The process is as follows




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.


Advantages and disadvantages of memory mapping


        memory-mapped IO The greatest advantage may be in performance, which is particularly important for the establishment of high-frequency electronic trading systems. Memory-mapped files are usually faster than standard access files through normal IO. Another great advantage is that memory-mapped IO allows the loading of potentially huge files that cannot be accessed directly. Experience has shown that memory-mapped IO performs better in large file processing. Even though it's not enough-the number of page faults is increased. Because the operating system loads only a subset of the files into memory, if a request page is not in memory, it will result in a page fault. It can also be used to share data in two of processes.

operating systems that support memory-mapped IO

        Most major operating systems such as Windows platforms, UNIX, Both Solaris and other Unix-like operating systems support memory-mapped IO and 64-bit architectures, and you can map almost any file to memory and access it directly through the Java programming language.

Java memory-mapped IO Essentials

Here are some points you need to know about Java memory Mapping:

Java supports memory-mapped IO through the Java.nio package. The
memory-mapped file is used primarily for performance-sensitive applications, such as high-frequency electronic trading platforms.
by using memory-mapped IO, you can load large files into memory. The
memory-mapped file may cause page requests to be incorrect if the requested page is not in memory. The
ability to map a file region depends on the size of the memory address. In a 32-bit machine, you cannot access more than 4GB or 2 ^ 32 (above the file). The
Memory-mapped IO is much faster than the IO stream in Java.
the memory used to load the file is outside the Java heap and resides in shared memory, allowing two different processes to share files. The
Memory-mapped file reads and writes are done by the operating system, so even if the Java program crashes after writing the content to memory, it will still write it to the file until the operating system resumes.
For performance reasons, it is recommended to use direct byte buffering instead of non-direct buffering.
Do not call the Mappedbytebuffer.force () method frequently, which means forcing the operating system to write memory content to disk, so if you call the Force () method every time you write a memory-mapped file, you will not appreciate the benefits of using mapped byte buffering. Instead, it (the performance) will resemble the performance of disk IO.

In case of a power failure or a host failure, there will be a small chance that a memory-mapped file is not written to disk, which means you may lose critical data.


Second, the example code

1, traditional IO read data, do not specify buffer size

 /** * Traditional IO read data, no buffer size specified * @author Linbingwen * @since September 5, 2015 * @param path * @return */ public static void ReadFile1 (String path) {Long start = System.currenttimemillis ();//start time file = NE          W File (path);              if (File.isfile ()) {BufferedReader bufferedreader = null;              FileReader filereader = null;                  try {filereader = new FileReader (file);                  BufferedReader = new BufferedReader (FileReader);                  String line = Bufferedreader.readline ();                  System.out.println ("========================== traditional IO reads data, using virtual machine heap memory ==========================");                      while (line! = null) {//rows read data System.out.println (lines);                  line = Bufferedreader.readline ();              }} catch (FileNotFoundException e) {e.printstacktrace (); } catch (IOException e) {E. Printstacktrace ();                      } finally {///Finally, be sure to close try {filereader.close ();                  Bufferedreader.close ();                  } catch (IOException e) {e.printstacktrace (); } Long end = System.currenttimemillis ();//End Time System.out.println ("traditional IO reads data, does not specify buffer size, total time consuming:            "+ (End-start) +" MS ");  }            }      }

2. Traditional IO reading data, specifying buffer size

 /** * Traditional IO read data, specify buffer size * @author Linbingwen * @since September 5, 2015 * @param path * @return * @  Throws FileNotFoundException */public static void ReadFile2 (String path) throws FileNotFoundException {Long start = System.currenttimemillis ();//start time int bufSize = 1024x768 * 1024x768 * 5;//5m buffer File fin = new File (path); File size 200MFileChannel fcin = new Randomaccessfile (FIN, "R"). Getchannel (); Bytebuffer Rbuffer = bytebuffer.allocate (bufSize); String enterstr = "\ n"; Long len = 0l;try {byte[] bs = new byte[bufsize]; String tempstring = Null;while (Fcin.read (rbuffer)! =-1) {//per read 5M to buffer int rsize = Rbuffer.position (); Rbuffer.rewind (); Rbuffer.get (BS);//Read buffer data into array rbuffer.clear ();//Clear buffer tempstring = new String (BS, 0, rsize); int fromIndex = 0;//buffer start int EndIndex = 0;//buffer end//read buffer data by row while ((EndIndex = Tempstring.indexof (Enterstr, fromIndex))! =-1) {String line = tempstring . substring (FromIndex, endIndex);//convert row System.out.print (line);            FromIndex = EndIndex + 1;}} LonG end = System.currenttimemillis ();//End Time System.out.println ("traditional IO reads data, specifies buffer size, total time elapsed:" + (End-start) + "MS");} catch (IOException e) {e.printstacktrace ();}}

3. Memory mapped Read file

/** * NIO Memory Map Read Large file * @author Linbingwen * @since September 15, 2015 * @param path */public static void ReadFile3 (String path) {L          Ong start = System.currenttimemillis ();//start time long filelength = 0;              Final int buffer_size = 0x300000;//3M Buffered File File = new file (path);              Filelength = File.length (); try {mappedbytebuffer inputbuffer = new Randomaccessfile (file, "R"). Getchannel (). Map (Filechannel.mapmode . READ_ONLY, 0, filelength);//Read large file byte[] DST = new byte[buffer_size];//reads 3M of content every time F or (int offset = 0; offset < filelength; offset + = Buffer_size) {if (Filelength-offset >= BU Ffer_size) {for (int i = 0; i < buffer_size; i++) dst[i] = input                      Buffer.get (offset + i); } else {for (int i = 0; i < Filelength-offset; i++) Dst[i] = i NpUtbuffer.get (offset + i); }//will get 3M content to Scanner, here XXX refers to Scanner parsing delimiter Scanner scan = new Scanner (New Bytea                      Rrayinputstream (DST)). Usedelimiter ("");  while (Scan.hasnext ()) {//Here is a method for parsing the read text System.out.print (Scan.next () +                      " ");                  } scan.close ();                } System.out.println ();            Long end = System.currenttimemillis ();//End Time System.out.println ("NIO memory mapping reads large files, total time:" + (End-start) + "MS");              } catch (Exception e) {e.printstacktrace ();  }      }

Third, test comparison

1.100M file

The file size is as follows:

The call is as follows:

public static void Main (string args[]) {string path = "D:" + file.separator + "Ces_t_msm_liq-trans-esp_20150702_01.dat"; 
   readfile1 (path);//readfile2 (path);//readfile3 (path);}


(1) Traditional IO reading data, not specifying buffer size, total time: 80264ms

Its memory is used as follows:

(2) Traditional IO read data, specify buffer size, total time: 80612ms

Its memory is used as follows:

(3) NIO memory map read large files, total time: 90955ms

Its memory is used as follows:


The analysis found that the memory map is not much faster than the traditional IO, or even slower, it may be because the disk IO operation more, but reduce its efficiency, memory mapping seems to be good for large file comparison. Small files are basically not much different.

2.1.2G file

Traditional IO reads data, does not specify buffer size, total time: 1245111ms


NIO memory Map read large files, total time consuming: 1223877ms (about 20 minutes multipoint)


Copyright NOTICE: This article for Bo Master Lin Bingwen Evankaka original article, reproduced please indicate the source Http://blog.csdn.net/evankaka

Java NIO Memory Map---g large file processing

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.