Skip to content
Related Articles

Related Articles

Improve Article

What is Memory-Mapped File in Java?

  • Last Updated : 11 Jun, 2021
Geek Week

Memory-mapped files are casual special files in Java that help to access content directly from memory. Java Programming supports memory-mapped files with java.nio package.  Memory-mapped I/O uses the filesystem to establish a virtual memory mapping from the user directly to the filesystem pages. It can be simply treated as a large array. Memory used to load Memory-mapped files is outside of Java Heap Space.

Here we use the MappedByteBuffer to read and write from memory. This utility can be used to create and store efficient memory-mapped files. Some major important features about MappedByteBuffer is as follows:

  1. MappedByteBuffer and file mapping remain valid until the garbage is collected. sun.misc.Cleaner is probably the only option available to clear memory-mapped files.
  2. Reading and writing in the memory-mapped file is generally done by the operating system to write content into a disk.
  3. Prefer Direct buffer to Indirect Buffer for better performance.
  4. Memory used to load File is outside Java heap and reside on shared memory which allows us to two different ways to access the file. By the way, this depends upon, whether you are using the direct or indirect buffer.

Let us do rollover through and implementing the same before concluding out merits and demerits of memory-mapped file

Example:

Java




// Java Program to illustrate Memory Mapped File via
// RandomAccessFile to open a file using FileChannel's map()
// method
 
// Importing standard classes from respective packages
import java.io.*;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Scanner;
 
// Main class
public class GFG {
 
    // The next line shows 10 MB as the max value of the
    // count
    private static int count = 10485760;
 
    // Main driver method
    public static void main(String[] args) throws Exception
    {
 
        // Display message asking user to enter the input
        // string
        System.out.print("enter character or string");
 
        // The method RandomAccessFile has an object sc and
        // is used to create a text file
 
        // Try block to check for exceptions
        try (RandomAccessFile sc
             = new RandomAccessFile("text.txt", "rw")) {
 
            // Scanner class to take objects input
            // Taking String a as input
            Scanner s = new Scanner(System.in);
 
            String a;
 
            a = s.next();
 
            // Mapping the file with the memory
            // Here the out is the object
            // This command will help us enable the read and
            // write functions
            MappedByteBuffer out = sc.getChannel().map(
                FileChannel.MapMode.READ_WRITE, 0, 10);
 
            // Writing into memory mapped file
            // taking it as 10 and printing it accordingly
            for (int i = 0; i < 10; i++) {
                System.out.println((out.put((byte)i)));
            }
 
            // Print the display message as soon
            // as the memory is done writing
            System.out.println(
                "Writing to Memory is complete");
 
            // Reading from memory mapped files
            // You can increase the size , it not be 10 , it
            // can be higher or lower Depeding on the size
            // of the file
            for (int i = 0; i < 10; i++) {
                System.out.println((char)out.get(i));
            }
 
            // Display message on the console showcasing
            // successful execution of the program
            System.out.println(
                "Reading from Memory is complete");
        }
    }
}

Output:



By far we have studied what and why we use memory-mapped files alongside have seen the implementation too. But with these merits, also do comes demerits which are shown below:

Merits of the memory-mapped file are as follows:

  • Performance: Memory-mapped Files are way faster than the standard ones.
  • Sharing latency: File can be shared, giving you shared memory between processes and can be more 10x lower latency than using a Socket over loopback.
  • Big Files: It allows us to showcase the larger files which are not accessible otherwise. They are much faster and cleaner.

Demerits of the memory-mapped file are as follows:

  • Faults: One of the demerits of the Memory Mapped File is its increasing number of page faults as the memory keeps increasing. Since only a little of it gets into memory, the page you might request if isn’t available into the memory may result in a page fault. But thankfully, most operating systems can generally map all the memory and access it directly using Java Programming Language.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :