I/O 高级

使用 MemorySegment 映射大于 2GB 的文件,支持确定性清理。

✕ 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
发现此代码有问题? 告诉我们。
📏

无大小限制

无需变通方案即可映射大于 2GB 的文件。

🧹

确定性清理

Arena 关闭时内存立即释放。

🔒

更安全的 API

MemorySegment 相比 ByteBuffer 提供更强的内存安全保证。

旧方式
MappedByteBuffer
现代方式
使用 Arena 的 MemorySegment
自 JDK
22
难度
高级
文件内存映射
可用

自 JDK 22 起可用(2024 年 3 月)

外部函数与内存 API(JEP 454)引入了带有 Arena 的 MemorySegment,解决了 MappedByteBuffer 的两个主要限制:2GB 大小限制和缺乏确定性清理。

分享 𝕏 🦋 in