Memory mapping in java is a low level concept to make file I/O more efficiently. Generally we use stream or buffer stream to do file I/O. Although buffered stream is widely used to increase the performance of file input and output, but memory mapping is the ultimate technique that can be used to increase the performance drastically. In memory map, the physical file is mapped with the memory and then the I/O is performed in the mapped memory directly. As a result the I/O is performed on the physical file itself. But you need to be careful about the memory usage. It is always recommended to map the memory in small chunks and then read/write on the file. It increases the performance and also releases the memory after use. If you want to map the entire big file into memory then it might hang the system itself.
In the following example, we will use RandomAccessFile to read and write. We will create a file channel and then use memory mapping to map the file with memory. Here MappedByteBuffer is a direct buffer to be used with file. While mapping you must mention the start and end point or reading or writing. This technique helps you to map a particular region of a file and perform the file I/O.
Sample code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package JavaTips.com;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
/**
*
* @author kaushikp
*/
public class JavaMemoryMap {
/**
* @param args the command line arguments
*/
static int length = 2048; // 128 Mb
public static void main(String[] args) throws Exception {
//Create RandomAccessFile and FileChannel
RandomAccessFile raf= new RandomAccessFile(“memorymaptest.dat”, “rw”);
FileChannel fc = raf.getChannel();
//Mapping the file using file channel
MappedByteBuffer mbb1 = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
MappedByteBuffer mbb2 = fc.map(FileChannel.MapMode.READ_WRITE, 1024, 2048);
//Writing content on the mapped file
for(int i = 0; i < 1024; i++)
mbb1.put((byte)’x’);
System.out.println(“Finished writing xxx”);
for(int i = 0; i < 1024; i++)
mbb2.put((byte)’y’);
System.out.println(“Finished writing yyy”);
}
}