What is Memory-Mapped File in Java?
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:
- 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.
- Reading and writing in the memory-mapped file is generally done by the operating system to write content into a disk.
- Prefer Direct buffer to Indirect Buffer for better performance.
- 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
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.