ZohebSiddiqui
ZohebSiddiqui

Reputation: 211

java.nio memory mapped file in java for reading huge file

Can anybody explain me the internal working of below code

public class MemoryMappedFileInJava {

private static int count = 10485760; //10 MB

public static void main(String[] args) throws Exception {

    RandomAccessFile memoryMappedFile = new RandomAccessFile("largeFile.txt", "rw");

    //Mapping a file into memory

    MappedByteBuffer out = memoryMappedFile.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, count);

    //Writing into Memory Mapped File
    for (int i = 0; i < count; i++) {
        out.put((byte) 'A');
    }

    System.out.println("Writing to Memory Mapped File is completed");



    //reading from memory file in Java
    for (int i = 0; i < 10 ; i++) {
        System.out.print((char) out.get(i));
    }

    System.out.println("Reading from Memory Mapped File is completed");

}

}

i have not understood few things file

1) what is MappedByteBuffer means how it internally works?

2)what is File Channel is it handle to the file which is need to perform the operations i.e read or write?

3)map() method what it actually maps?

4)how this approach is faster than using java.io file read and write?

5)Is this approach is only useful, only when say i have a heap size of 400MB and i need to read a file which is of 8GB . or i can use it any time?

6) in the above code reading and writing is taking byte by byte,how can it be fast please explain?

Upvotes: 2

Views: 1469

Answers (1)

user207421
user207421

Reputation: 310885

What is MappedByteBuffer means how it internally works?

It is a Java wrapper around a memory area allocated by the operating system which is mapped to the file, usually on a paging basis. So the memory area appears to contain the file's contents, and changes to it are written back to the file.

What is File Channel is it handle to the file which is need to perform the operations i.e read or write?

Yes.

map() method what it actually maps?

The file to memory, or memory to the file, whichever way you prefer to think of it.

How this approach is faster than using java.io file read and write?

It bypasses a lot of the OS file system.

Is this approach is only useful, only when say i have a heap size of 400MB and i need to read a file which is of 8GB . or i can use it any time?

You can use it any time, within limits, but it's really only of benefit on large files. The performance gain was only 20% or so last time I measured it.

In the above code reading and writing is taking byte by byte,how can it be fast please explain?

Because of paging.

Upvotes: 3

Related Questions