โ— Shell
clean mode source โ†—

File memory mapping

Home / I/O / File memory mapping

Code Comparison

try (FileChannel channel =
    FileChannel.open(path,
        StandardOpenOption.READ,
        StandardOpenOption.WRITE)) {
    MappedByteBuffer buffer =
        channel.map(
            FileChannel.MapMode.READ_WRITE,
            0, (int) channel.size());
    // Limited to 2GB
    // Freed by GC, no control
}
FileChannel channel =
    FileChannel.open(path,
        StandardOpenOption.READ,
        StandardOpenOption.WRITE);
try (Arena arena = Arena.ofShared()) {
    MemorySegment segment =
        channel.map(
            FileChannel.MapMode.READ_WRITE,
            0, channel.size(), arena);
    // No size limit
    // ...
} // Deterministic cleanup

Why the modern way wins

๐Ÿ“

No size limit

Map files larger than 2GB without workarounds.

๐Ÿ”’

Deterministic cleanup

Arena ensures memory is freed at scope exit, not GC time.

โšก

Better performance

Aligned with modern memory models and hardware.

Old Approach

MappedByteBuffer

Modern Approach

MemorySegment with Arena

JDK Support

File memory mapping

Available

Available since JDK 22 (March 2024)

How it works

The Foreign Function & Memory API (JEP 454) introduces MemorySegment for safe and efficient memory access. Unlike MappedByteBuffer, MemorySegment supports files larger than 2GB (Integer.MAX_VALUE), provides deterministic cleanup via Arena, and offers better performance with modern hardware.

Related Documentation

Proof