-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathfile-memory-mapping.yaml
More file actions
67 lines (67 loc) · 2.25 KB
/
file-memory-mapping.yaml
File metadata and controls
67 lines (67 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
---
id: 97
slug: "file-memory-mapping"
title: "File memory mapping"
category: "io"
difficulty: "advanced"
jdkVersion: "22"
oldLabel: "Java 8"
modernLabel: "Java 22+"
oldApproach: "MappedByteBuffer"
modernApproach: "MemorySegment with Arena"
oldCode: |-
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
}
modernCode: |-
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
summary: "Map files larger than 2GB with deterministic cleanup using MemorySegment."
explanation: "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."
whyModernWins:
- icon: "📏"
title: "No size limit"
desc: "Map files larger than 2GB without workarounds."
- icon: "🔒"
title: "Deterministic cleanup"
desc: "Arena ensures memory is freed at scope exit, not GC time."
- icon: "⚡"
title: "Better performance"
desc: "Aligned with modern memory models and hardware."
support:
state: "available"
description: "Available since JDK 22 (March 2024)"
prev: "io/try-with-resources-effectively-final"
next: "io/files-mismatch"
related:
- "io/http-client"
- "io/reading-files"
- "io/writing-files"
docs:
- title: "MemorySegment (Java 22)"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/foreign/MemorySegment.html"
- title: "Arena (Java 22)"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/foreign/Arena.html"
- title: "JEP 454: Foreign Function & Memory API"
href: "https://openjdk.org/jeps/454"