File memory mapping
Map files larger than 2GB with deterministic cleanup using MemorySegment.
Code Comparison
✕ Java 8
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
}
✓ Java 22+
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
Since JDK
22
Difficulty
advanced
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