Java › I/O & NIO
How would you implement memory-mapped file I/O using MappedByteBuffer, and what performance advantage does this provide for very large files compared to traditional stream-based reading?
AdvancedAnswer
Memory-mapped I/O (via FileChannel.map()) maps a region of a file directly into the process's virtual memory address space, letting you read/write file contents through simple memory access (via a MappedByteBuffer) rather than explicit read()/write() system calls -- the OS's virtual memory system handles paging file content in and out of physical memory transparently and lazily as needed (only the specific pages actually accessed are loaded, not the entire file upfront), which can provide substantial performance benefits for large files with sparse/random access patterns (avoiding the overhead of many separate read() calls, and letting the OS's own page cache do the heavy lifting) though it introduces its own complexities around resource cleanup and platform-specific behavior (particularly around unmapping, which historically had no clean, guaranteed API before newer JDK versions improved this).
try (FileChannel channel = FileChannel.open(Path.of("large_data.bin"), StandardOpenOption.READ)) {
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
// Access file content directly as memory -- OS pages content in/out transparently as accessed
byte firstByte = buffer.get(0);
byte middleByte = buffer.get(channel.size() / 2); // random access, only that specific page gets loaded
}Real-world example A database engine implementing its own storage layer uses memory-mapped files for its data files, letting the OS's virtual memory system handle efficient paging of a multi-gigabyte file that's far larger than available physical RAM, avoiding the overhead of explicit read() calls for the engine's characteristically random access patterns across the file.