Video in progress
How did the Foreign Function & Memory API (Java 22) change working with off-heap memory compared to ByteBuffer and Unsafe?
The FFM API (JEP 454, final in Java 22) manages off-heap memory safely and explicitly through MemorySegment and Arena: there are bounds checks, memory is freed immediately when the arena closes, and there is no 2 GB limit. With ByteBuffer, freeing depended on the GC, and Unsafe gave no protection at all.
📖 Answer
The problems of the two earlier ways:
ByteBuffer.allocateDirect: the index is anint, so one buffer is up to 2 GB. The memory is freed only when the buffer object is collected by the GC (through the Cleaner), and you don't know when that will be.sun.misc.Unsafe.allocateMemory: fast and unrestricted, but a wrong address crashes the JVM, and forgettingfreeMemoryis a leak. These methods are now deprecated (JEP 471).
With FFM:
try (Arena arena = Arena.ofConfined()) {
MemorySegment seg = arena.allocate(ValueLayout.JAVA_LONG, 1_000_000);
for (long i = 0; i < 1_000_000; i++) {
seg.setAtIndex(ValueLayout.JAVA_LONG, i, i * 2);
}
long v = seg.getAtIndex(ValueLayout.JAVA_LONG, 999_999);
} // the memory is freed right here
What improved:
- Deterministic freeing. When the arena closes, the segments die; accessing one after that gives
IllegalStateException, not a crash. - Thread safety.
ofConfined: only the creating thread;ofShared: many threads;ofAuto: managed by the GC;global: forever. - Bounds checks and
longindices: big segments. - File mapping:
FileChannel.map(..., arena)now returns aMemorySegmentwithout the 2 GB limit.
The second half of the API is calling native functions without JNI (Linker, SymbolLookup, jextract).
The cost: the code is longer than with ByteBuffer, and it was still a preview in Java 21, so on prod you need Java 22+. Native calls require --enable-native-access, otherwise a warning appears.
Where you need it: big off-heap caches, I/O libraries like Netty/Kafka, integration with a native library. In an ordinary service, rarely.
Sign up to mark studied questions and save your progress.