Video in progress

Your codebase has parts that work off-heap with `MappedByteBuffer`, `sun.misc.Unsafe` and direct buffers. Should you move to the Foreign Function & Memory API, and how do you plan it?

Yes, in the long term: the FFM API is final from Java 22, while the memory methods of Unsafe are being deprecated step by step and are headed for removal. MemorySegment and Arena give safer off-heap memory with no 2 GB limit and an explicit lifecycle. The migration: put the boundary behind an abstraction, measure, and go step by step.

📖 Answer

Why move:

  • The memory-access methods of sun.misc.Unsafe are deprecated for removal by JEP 471 (Java 23). In later versions they will first give warnings, then errors. This will be a blocker on your path to upgrading Java.
  • ByteBuffer is limited to 2 GB and can't be freed explicitly. MemorySegment works with long offsets, and when an Arena.ofConfined() or ofShared() is closed, the memory and mappings are released immediately.
  • Going out of bounds and touching closed memory throw an exception, not a JVM crash.
try (Arena arena = Arena.ofConfined();
     FileChannel ch = FileChannel.open(index, READ)) {
    MemorySegment seg = ch.map(FileChannel.MapMode.READ_ONLY, 0, ch.size(), arena);
    long v = seg.get(ValueLayout.JAVA_LONG_UNALIGNED, slot * 8L);
} // the mapping is closed here

The plan:

  1. Inventory. Where are Unsafe, allocateDirect, map and JNI used? Often half of them are not your code but in libraries (Netty, Chronicle, Lucene), and for those the upgrade path lies with the library itself.
  2. Minimum version. FFM needs Java 22+. If prod is still on 21 LTS, you plan the runtime upgrade first; 25 LTS is the natural target.
  3. Abstraction. Keep the off-heap code behind one module (an OffHeapIndex interface). Keep both implementations side by side and switch with a feature flag.
  4. Measuring. MemorySegment accesses are well optimized by the JIT, but there are bounds checks and thread-confinement checks. Compare the hot loops with JMH, and don't forget the cost of closing a shared arena.
  5. Lifecycle design. The biggest change is not technical but conceptual: instead of "the GC will free it someday", you have to define clearly who opens the arena and who closes it. In a bad design, touching a closed segment throws IllegalStateException; that is good, because before it was a silent crash or corrupted data.

If the off-heap code is small and stable, there is no need to hurry, but put it in the plan for the move to the next LTS anyway.