Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

How do memory-mapped files work in Java with FileChannel.map? What are their benefits and their known problems?

FileChannel.map asks the operating system to map a region of a file into the process's address space and returns a MappedByteBuffer whose bytes are the file's pages in the OS page cache. Reading and writing it are plain memory accesses, and the OS loads pages on first touch and writes dirty pages back later, which makes mapping fast for large files with random access and for sharing data between processes. Its known problems are the 2 GB limit per MappedByteBuffer because of int indexes, no supported way to unmap before the FFM API, which can keep files locked on Windows, and page faults that stall threads unpredictably; FileChannel.map with an Arena returns a MemorySegment that can be larger and is unmapped deterministically.

Why this question is asked

Memory-mapped files power some of the fastest software written in Java: message brokers, search indexes, time-series stores and low-latency caches. They also produce some of the strangest bugs, such as a thread that freezes for milliseconds on what looks like an array read, or a file that cannot be deleted on Windows until the JVM exits. Interviewers ask this internals question to see whether we understand what the operating system is doing underneath the buffer. In this answer, we will recap virtual memory and the page cache, see what FileChannel.map does and how reads and writes become page operations, discuss where mapping shines, and then go through its problems and how the Foreign Function and Memory API addresses them.

1A Quick Recap of Virtual Memory and the Page Cache

A process does not see physical memory directly. It sees a virtual address space, and the operating system maps pieces of that space, called pages and usually 4 KB in size, to physical memory on demand. When a program touches an address whose page is not in memory, the CPU raises a page fault, the kernel finds or loads the data, sets up the mapping and lets the program continue.

The page cache is the kernel's cache of file contents in memory. When we read a file with ordinary read() calls, the kernel loads its pages into the page cache and then copies the requested bytes into our buffer. Memory mapping skips that copy: it maps the page cache pages straight into our address space, so our process and the cache share the same physical memory.

2What FileChannel.map Does

FileChannel.map(mode, position, size) calls the operating system's mmap. It reserves a range of virtual addresses for that region of the file and returns a MappedByteBuffer, a direct buffer whose address points at that range. No data is read at this point; the mapping is lazy. The mode decides what is allowed: READ_ONLY, READ_WRITE where writes go back to the file, or PRIVATE where writes stay in a private copy and never reach the file.

Java
try (FileChannel ch = FileChannel.open(Path.of("index.dat"), READ, WRITE)) {
MappedByteBuffer buf = ch.map(FileChannel.MapMode.READ_WRITE, 0, ch.size());
long v = buf.getLong(8 * 1_000_000); // first touch of that page: page fault, OS loads 4 KB
long w = buf.getLong(8 * 1_000_001); // same page: a plain memory read, a few ns
buf.putLong(0, 42L); // marks the page dirty; OS writes it back later
buf.force(); // optional: write dirty pages to disk now
}
// The mapping stays valid after the channel is closed, until the buffer is unmapped
Step throughWhat happens on buf.getLong(offset)
  1. Java reads memory at base + offset
  2. Is the page mapped in this process?
    Yesreturn the value: a plain memory readNopage fault into the kernel
  3. Is the page in the page cache?
    Yesmap it (minor fault, microseconds)Noread 4 KB or more from disk (major fault)
  4. Thread resumes and reads the value

4 steps in order. Play them, or step through them one at a time.

Notice that after the mapping is set up, Java code just reads and writes memory. There is no system call per access. The first access to each page costs a page fault, and if the page is not already in the page cache, a disk read. Later accesses to that page are as fast as any memory read. Writes mark the page dirty, and the kernel writes dirty pages back to the file at a time of its choosing, or when we call force().

3Where Mapping Shines

Mapping suits large files accessed at random, such as an index where each lookup touches a few pages scattered across gigabytes. We avoid a system call and a copy per lookup, the kernel keeps hot pages cached automatically, and the memory used does not count against the Java heap, so the garbage collector never scans it. It also suits sharing between processes: two processes that map the same file see the same physical pages, so a write by one is visible to the other without any copying, which some low-latency messaging libraries build on. And because the data lives in the page cache, it survives a JVM restart, so a restarted service starts warm.

4The Known Problems

The first problem is size. ByteBuffer uses int for positions and limits, so one MappedByteBuffer can cover at most Integer.MAX_VALUE bytes, about 2 GB. To map a 40 GB file we would need twenty mappings and code that splits every access across their boundaries, which is a common source of bugs when a record straddles two mappings.

The second problem is unmapping. Before the FFM API, Java had no supported way to release a mapping. The mapping is released only when the MappedByteBuffer object is garbage collected, which may take a long time. Until then the virtual address space and the file mapping stay in use, and on Windows a mapped file cannot be deleted or truncated, so tests that create and delete mapped files fail and long-running services cannot rotate their files. Libraries used to call an internal cleaner method through reflection to force an unmap, which is unsupported, blocked by strong encapsulation in recent JDKs, and dangerous, because any later access to the buffer crashes the JVM.

The third problem is latency. A page fault can happen on any access, in the middle of business logic, and a major fault waits for the disk, which can take tens of microseconds on an NVMe drive and milliseconds on network or cloud block storage. The thread simply stalls, and during such a fault it cannot reach a safepoint, which can delay garbage collection pauses for all threads. Writes have a similar issue: when many pages are dirty, the kernel may throttle writers. Profilers see this as time spent in an ordinary memory access, which makes it hard to diagnose.

5The FFM API: Larger Mappings and Deterministic Unmapping

The Foreign Function and Memory API, final since Java 22, adds an overload FileChannel.map(mode, offset, size, arena) that returns a MemorySegment instead of a buffer. MemorySegment uses long offsets, so one segment can map the whole 40 GB file. An Arena controls the lifetime of the memory it allocates or maps: when we close a confined or shared arena, every segment it owns is unmapped immediately, and any later access throws an IllegalStateException instead of crashing the JVM.

Java
try (FileChannel ch = FileChannel.open(Path.of("big.dat"), READ);
Arena arena = Arena.ofShared()) { // usable by many threads
MemorySegment seg = ch.map(FileChannel.MapMode.READ_ONLY, 0, ch.size(), arena);
System.out.println(seg.byteSize()); // 42949672960 (40 GB)
long v = seg.get(ValueLayout.JAVA_LONG_UNALIGNED, 30_000_000_000L); // offset beyond 2 GB
} // arena closed: the mapping is released here, not at some future GC

The page cache behaviour is the same as before, so page faults still cost what they cost; FFM fixes the size limit and the lifetime problem, not the latency.

6Follow-up questions

How does an Arena make unmapping deterministic?

An Arena owns the memory segments created through it and has an explicit lifetime. When we call close(), usually through try-with-resources, it unmaps every mapped segment at that moment. To stay safe, a confined arena can only be used by its owning thread, and a shared arena coordinates with other threads before closing, so no thread can still be reading the memory being released; accesses after close fail with an exception. The automatic arena from Arena.ofAuto() goes back to GC-driven release, which is useful when deterministic lifetime does not matter.

Does a mapped file count as Java heap?

No. Mapped memory is outside the heap and is not limited by -Xmx or MaxDirectMemorySize. It shows up in the process's resident memory as the pages are touched, and the JVM reports it in the mapped buffer pool of BufferPoolMXBean for MappedByteBuffer mappings. In containers, how mapped file pages count against the memory limit depends on the platform's accounting, so it must be checked.

7Conclusion

In this answer, we saw that FileChannel.map maps a file's pages from the OS page cache into the process, so reads and writes become memory accesses while the OS loads pages on demand and writes dirty pages back. That makes mapping fast for large random-access files and for sharing between processes. Its problems are the 2 GB limit of MappedByteBuffer, unmapping that depends on garbage collection and can lock files on Windows, and page faults that stall threads unpredictably; the FFM API's map with an Arena returns a large MemorySegment and releases it deterministically, but does not remove page fault latency.

What to say in the interviewAbout 100 seconds aloud

Open with

FileChannel.map calls the operating system's mmap: it maps a region of the file into the process's virtual address space and gives me a MappedByteBuffer that points at it.

Then, if they want more

The bytes are really the file's pages in the OS page cache, so there is no copy and no system call per access.

Nothing is read up front; the first time I touch a page I get a page fault, the kernel maps the page in, reading it from disk if it is not cached, and after that accesses to that page are plain memory reads. Writes mark pages dirty and the kernel writes them back later, or when I call force.

This is great for large files with random access, like indexes, because hot pages stay cached by the OS, the memory is off-heap so the GC never scans it, and processes mapping the same file share the same pages.

The problems: a MappedByteBuffer uses int indexes, so one mapping is limited to about 2 GB and big files need many mappings. Before FFM there was no supported way to unmap; release waited for the buffer to be garbage collected, which on Windows keeps the file locked so it cannot be deleted.

And page faults can stall a thread at any access, for milliseconds on slow storage, which shows up as unexplained latency. With the FFM API, FileChannel.map with an Arena returns a MemorySegment with long offsets, so one segment can cover the whole file, and closing the arena unmaps it right away.

About this answer

Last updated
12 November 2026
Versions it names
Java 22
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How do memory-mapped files work in Java with FileChannel.map? What are their benefits...": https://scrivio-interview-library.netlify.app/java/io-and-nio/a3b7b8f034/