Video in progress
What is a memory-mapped file (MappedByteBuffer), when is it useful, and what are the risks?
FileChannel.map attaches the file to the process's virtual memory: reading from the buffer becomes reading straight from the OS page cache, with no system call and no copy. It is very fast for random access to big files, but unmapping is not under your control, and if the file shrinks, the process can crash.
📖 Answer
try (FileChannel ch = FileChannel.open(path, StandardOpenOption.READ)) {
MappedByteBuffer mb = ch.map(FileChannel.MapMode.READ_ONLY, 0, ch.size());
long value = mb.getLong(8_000_000); // the OS loads the needed page itself
}
Where it is used: index files (Lucene/Elasticsearch), Kafka's segment indexes, low-latency logs like Chronicle Queue. Several processes can also map the same file and exchange data through memory.
Problems:
- a
ByteBufferis indexed by an int, so a single mapping can't be larger than 2 GB. A big file is mapped in several chunks (in Java 22+,MemorySegmenthas no such limit); - the mapping outlives the channel and is released only when the GC collects the buffer. On Windows you can't delete the file until then;
- if another process truncates the file, touching a page that no longer exists gives SIGBUS: the JVM throws
InternalErroror crashes outright; - while a page is loading from disk (a page fault) the thread blocks, but this doesn't show up as IO in a profiler, so latency spikes are hard to find;
- RSS looks big; in a container this is the page cache, but monitoring may give a misleading signal.
For a single sequential read, mmap barely beats ordinary buffered reading. Its benefit is many random accesses to the same data.
Sign up to mark studied questions and save your progress.