Foreign Function and Memory API

The Foreign Function and Memory (FFM) API lets Java code allocate and access memory outside the heap safely, and call native C libraries without writing JNI glue code. It lives in java.lang.foreign and became standard in Java 22 (JEP 454). This page explains its four building blocks, then shows segments, layouts, threads, mapped files, native calls with callbacks, errno and varargs, and what the safety checks cost.

Contents

What the FFM API is for

Objects on the Java heap are managed by the garbage collector, which is what you want almost all of the time. Some programs need memory the collector does not manage, or need to call code written in C:

  • very large buffers, such as caches of many gigabytes, that would make garbage collection slower if they lived on the heap;
  • data exchanged with native libraries, such as a database engine, an image codec or a machine-learning runtime;
  • memory-mapped files larger than 2 GB.

Before Java 22 each option had a real drawback. ByteBuffer.allocateDirect is limited to 2 GB per buffer and its memory is freed only when the collector notices the buffer object is unreachable. sun.misc.Unsafe is unsupported and unchecked, so a wrong address crashes the JVM. JNI needs C glue code compiled separately for each platform.

The Foreign Function and Memory (FFM) API in java.lang.foreign replaces them with a few concepts that fit together:

  • MemorySegment: a contiguous region of memory, on or off the heap, with a size. Every access is checked against that size.
  • Arena: controls the lifetime of segments. Closing an arena frees all its segments at once, and any later access throws instead of reading freed memory.
  • MemoryLayout: describes the shape of data, like a C struct, and computes sizes, offsets and alignment.
  • Linker: turns a native function into a MethodHandle (a downcall) and a Java method into a C function pointer (an upcall).

The JIT compiles segment accesses to plain memory loads and stores after removing the checks it can prove unnecessary, so the safety costs little, as a measurement below shows.

History of the FFM API
JDKJEPStatus
14 to 16JEP 370, 383, 393, 389Separate incubators for memory access and the foreign linker
17, 18JEP 412, 419Combined incubator
19, 20, 21JEP 424, 434, 442Preview
22JEP 454Standard

On Java 21 the same code needs --enable-preview, and some names differ, such as allocateUtf8String instead of allocateFrom. The programs here were compiled and run on JDK 25 on Linux x86-64.

MemorySegment and Arena

An Arena allocates segments and frees all of them when it is closed. Arena.ofConfined() gives an arena that one thread may use, closed by try-with-resources. Every access to a segment is checked: it must be within bounds, and the arena must still be open.

The program writes the squares 1 to 25 into five ints of off-heap memory, writes through a slice, tests both checks, and stores a C string. "héllo" was chosen because é takes two bytes in UTF-8, so the byte count differs from the character count.

Java
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;

public class Segments {

    public static void main(String[] args) {
        MemorySegment escaped;
        try (Arena arena = Arena.ofConfined()) {
            // 5 ints of off-heap memory, zero-filled
            MemorySegment ints = arena.allocate(ValueLayout.JAVA_INT, 5);
            for (int i = 0; i < 5; i++) {
                ints.setAtIndex(ValueLayout.JAVA_INT, i, (i + 1) * (i + 1));
            }
            System.out.println("size in bytes: " + ints.byteSize());
            System.out.print("values:");
            for (int i = 0; i < 5; i++) {
                System.out.print(" " + ints.getAtIndex(ValueLayout.JAVA_INT, i));
            }
            System.out.println();

            // A slice is a view of part of the segment, sharing the same memory
            MemorySegment lastTwo = ints.asSlice(3 * 4L, 2 * 4L);
            lastTwo.setAtIndex(ValueLayout.JAVA_INT, 0, -1);
            System.out.println("after writing through the slice, index 3 = "
                    + ints.getAtIndex(ValueLayout.JAVA_INT, 3));

            // Every access is bounds-checked
            try {
                ints.getAtIndex(ValueLayout.JAVA_INT, 5);
            } catch (IndexOutOfBoundsException e) {
                System.out.println("index 5: IndexOutOfBoundsException");
            }

            // C strings: UTF-8 bytes plus a terminating zero byte
            MemorySegment text = arena.allocateFrom("héllo");
            System.out.println("C string bytes: " + text.byteSize() + ", reads back equal: "
                    + text.getString(0).equals("héllo"));
            escaped = ints;
        }

        // The arena is closed, so its memory has been freed
        System.out.println("segment still alive? " + escaped.scope().isAlive());
        try {
            escaped.getAtIndex(ValueLayout.JAVA_INT, 0);
        } catch (IllegalStateException e) {
            System.out.println("access after close: IllegalStateException");
        }
    }
}

Output:

Output
size in bytes: 20
values: 1 4 9 16 25
after writing through the slice, index 3 = -1
index 5: IndexOutOfBoundsException
C string bytes: 7, reads back equal: true
segment still alive? false
access after close: IllegalStateException
  1. Five ints take 20 bytes. Memory from allocate is zero-filled.
  2. The slice covers bytes 12 to 19, which are elements 3 and 4. Writing -1 to the slice's first element changed element 3 of the original, because a slice shares memory.
  3. Reading element 5 of a 5-element segment throws IndexOutOfBoundsException instead of reading whatever lies beyond it.
  4. allocateFrom(String) stores UTF-8 bytes plus a terminating zero: 1 + 2 + 3 + 1 = 7 bytes.
  5. After the try block, the arena is closed and its memory freed immediately, not when the GC runs. The segment reference still exists, but any access throws IllegalStateException, so a use-after-free bug becomes an exception instead of memory corruption.
Arena kinds
ArenaFreed whenThreads
Arena.ofConfined()close()Only the owner thread
Arena.ofShared()close()Any thread
Arena.ofAuto()The GC finds it unreachableAny thread
Arena.global()NeverAny thread

Structured memory with layouts

Computing byte offsets by hand is error-prone. A MemoryLayout describes the shape of the data, like a C struct, and computes sizes and offsets. A VarHandle made from a layout path reads and writes one named field. The program describes struct Point { int x; int y; double weight; } and an array of three of them.

Java
import java.lang.foreign.Arena;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemoryLayout.PathElement;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SequenceLayout;
import java.lang.foreign.StructLayout;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.VarHandle;

public class StructLayouts {

    // struct Point { int x; int y; double weight; } as a C compiler would lay it out
    static final StructLayout POINT = MemoryLayout.structLayout(
            ValueLayout.JAVA_INT.withName("x"),
            ValueLayout.JAVA_INT.withName("y"),
            ValueLayout.JAVA_DOUBLE.withName("weight"));

    static final SequenceLayout POINTS = MemoryLayout.sequenceLayout(3, POINT);

    // Handles that address one field of element i: coordinates (segment, base offset, index)
    static final VarHandle X = POINTS.varHandle(PathElement.sequenceElement(),
            PathElement.groupElement("x"));
    static final VarHandle Y = POINTS.varHandle(PathElement.sequenceElement(),
            PathElement.groupElement("y"));
    static final VarHandle WEIGHT = POINTS.varHandle(PathElement.sequenceElement(),
            PathElement.groupElement("weight"));

    public static void main(String[] args) {
        System.out.println("Point size " + POINT.byteSize() + " bytes, offset of weight "
                + POINT.byteOffset(PathElement.groupElement("weight")));
        System.out.println("array of 3 points: " + POINTS.byteSize() + " bytes");

        try (Arena arena = Arena.ofConfined()) {
            MemorySegment points = arena.allocate(POINTS);
            for (long i = 0; i < 3; i++) {
                X.set(points, 0L, i, (int) i * 10);
                Y.set(points, 0L, i, (int) i * 10 + 5);
                WEIGHT.set(points, 0L, i, 1.5 * (i + 1));
            }
            for (long i = 0; i < 3; i++) {
                System.out.printf("point %d: x=%d y=%d weight=%.1f%n", i,
                        (int) X.get(points, 0L, i), (int) Y.get(points, 0L, i),
                        (double) WEIGHT.get(points, 0L, i));
            }
        }
    }
}

Output:

Output
Point size 16 bytes, offset of weight 8
array of 3 points: 48 bytes
point 0: x=0 y=5 weight=1.5
point 1: x=10 y=15 weight=3.0
point 2: x=20 y=25 weight=4.5
  • Two 4-byte ints and an 8-byte double make 16 bytes, with weight at offset 8. Three points take 48 bytes.
  • Each handle from a sequence layout takes three coordinates: the segment, a base offset (0 here) and the element index. The handle computes base + index × 16 + field offset for you.
  • The layout must match what the C side expects, including padding. If a double followed a single int, you would add MemoryLayout.paddingLayout(4) to keep the double 8-byte aligned, and the API rejects misaligned layouts.

Arenas and threads, and heap segments

The arena kind decides which threads may use a segment. The program writes to a confined segment from a second thread, has four threads fill a shared segment, and copies a Java array into native memory.

Java
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.util.concurrent.atomic.AtomicReference;

public class ArenaThreads {

    public static void main(String[] args) throws Exception {
        // A confined segment may only be touched by the thread that owns the arena
        try (Arena confined = Arena.ofConfined()) {
            MemorySegment seg = confined.allocate(ValueLayout.JAVA_LONG);
            AtomicReference<String> seen = new AtomicReference<>();
            Thread t = Thread.ofPlatform().start(() -> {
                try {
                    seg.set(ValueLayout.JAVA_LONG, 0, 1L);
                    seen.set("write succeeded");
                } catch (WrongThreadException e) {
                    seen.set("WrongThreadException");
                }
            });
            t.join();
            System.out.println("other thread writing a confined segment: " + seen.get());
        }

        // A shared arena allows any thread; close() waits for no one, so join first
        try (Arena shared = Arena.ofShared()) {
            MemorySegment counters = shared.allocate(ValueLayout.JAVA_LONG, 4);
            Thread[] workers = new Thread[4];
            for (int w = 0; w < 4; w++) {
                int slot = w;
                workers[w] = Thread.ofPlatform().start(() -> {
                    for (int i = 0; i < 1000; i++) {
                        long v = counters.getAtIndex(ValueLayout.JAVA_LONG, slot);
                        counters.setAtIndex(ValueLayout.JAVA_LONG, slot, v + 1);
                    }
                });
            }
            for (Thread w : workers) {
                w.join();
            }
            long[] values = counters.toArray(ValueLayout.JAVA_LONG);
            System.out.println("shared arena, one slot per thread: "
                    + java.util.Arrays.toString(values));
        }

        // Heap segments wrap Java arrays; copy moves data between heap and native memory
        int[] onHeap = {5, 6, 7, 8};
        MemorySegment heapSeg = MemorySegment.ofArray(onHeap);
        try (Arena arena = Arena.ofConfined()) {
            MemorySegment nativeSeg = arena.allocate(ValueLayout.JAVA_INT, 4);
            MemorySegment.copy(heapSeg, 0, nativeSeg, 0, heapSeg.byteSize());
            nativeSeg.setAtIndex(ValueLayout.JAVA_INT, 0, 50);
            System.out.println("heap segment native? " + heapSeg.isNative()
                    + ", native copy: " + java.util.Arrays.toString(
                    nativeSeg.toArray(ValueLayout.JAVA_INT)) + ", array unchanged: "
                    + onHeap[0]);
        }
    }
}

Output:

Output
other thread writing a confined segment: WrongThreadException
shared arena, one slot per thread: [1000, 1000, 1000, 1000]
heap segment native? false, native copy: [50, 6, 7, 8], array unchanged: 5
  • The other thread got WrongThreadException: a confined arena's segments belong to the thread that created the arena. That rule lets the JVM check liveness cheaply.
  • With Arena.ofShared(), four threads each counted to 1,000 in their own slot. A shared arena does not make access atomic; each thread used a different slot, so no updates were lost. For counters shared between threads, use a VarHandle with atomic access modes. If the arena is closed while other threads still use it, their next access throws IllegalStateException, so join the workers before closing.
  • MemorySegment.ofArray wraps a Java array as a heap segment (isNative() is false). MemorySegment.copy moved its 16 bytes to native memory, and writing 50 there left the array's 5 unchanged.

Memory-mapping a file into a segment

FileChannel.map has an overload that takes an arena and returns a MemorySegment. Unlike the older MappedByteBuffer, it is not limited to 2 GB and it is unmapped when the arena closes. The program maps a 4 MB file of one million big-endian ints, the byte order most file formats use, and checks the bytes on disk.

Java
import java.io.IOException;
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class MappedFile {

    // Unaligned big-endian int, the byte order most file formats use
    static final ValueLayout.OfInt BE_INT =
            ValueLayout.JAVA_INT_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN);

    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("records", ".bin");
        long records = 1000000;                 // 4 MB of big-endian ints
        try (FileChannel ch = FileChannel.open(file, StandardOpenOption.READ,
                StandardOpenOption.WRITE);
                Arena arena = Arena.ofConfined()) {
            // map(..., arena) returns a MemorySegment: no 2 GB limit, unmapped on close
            MemorySegment map = ch.map(FileChannel.MapMode.READ_WRITE, 0, records * 4, arena);
            for (long i = 0; i < records; i++) {
                map.set(BE_INT, i * 4, (int) i);
            }
            map.force();                          // flush the pages to the file
            System.out.println("mapped segment: " + map.byteSize() + " bytes, native "
                    + map.isNative());
            System.out.println("record 999,999 = " + map.get(BE_INT, 999999 * 4));
        }
        byte[] head = Files.readAllBytes(file);
        System.out.println("file size " + head.length + ", bytes of record 1: "
                + head[4] + " " + head[5] + " " + head[6] + " " + head[7]);
        Files.delete(file);
    }
}

Output:

Output
mapped segment: 4000000 bytes, native true
record 999,999 = 999999
file size 4000000, bytes of record 1: 0 0 0 1
  • The mapped segment is 4,000,000 bytes and counts as native memory. Record 999,999 read back correctly through the same layout.
  • JAVA_INT_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN) made the file's bytes for record 1 come out as 0 0 0 1, most significant byte first, regardless of the CPU's own byte order. The UNALIGNED variant allows offsets that are not multiples of 4, which binary file formats often need.
  • force() wrote the changed pages back to the file before it was read with Files.readAllBytes. See handling large files for more on mapping.

Calling C functions

The Linker turns a native function into a MethodHandle (a downcall). You find the function's address with a symbol lookup and describe its C signature with a FunctionDescriptor. The program calls two functions from the C standard library:

  • strlen, a simple call with a pointer argument;
  • qsort, which needs a pointer to a comparison function. upcallStub turns a Java method into a C function pointer, so C code calls back into Java to compare elements.

The array {42, 7, 19, 3, 88, 1} is unordered so the sort is visible.

Java
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.Arrays;

public class CallC {

    static final Linker LINKER = Linker.nativeLinker();

    // A Java method that C will call back: int compare(const int*, const int*)
    static int compareInts(MemorySegment a, MemorySegment b) {
        return Integer.compare(a.get(ValueLayout.JAVA_INT, 0), b.get(ValueLayout.JAVA_INT, 0));
    }

    @SuppressWarnings("restricted")    // javac flags native calls; we accept that knowingly
    public static void main(String[] args) throws Throwable {
        // size_t strlen(const char *s)
        MethodHandle strlen = LINKER.downcallHandle(
                LINKER.defaultLookup().find("strlen").orElseThrow(),
                FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));

        // void qsort(void *base, size_t n, size_t size, int (*cmp)(const void*, const void*))
        MethodHandle qsort = LINKER.downcallHandle(
                LINKER.defaultLookup().find("qsort").orElseThrow(),
                FunctionDescriptor.ofVoid(ValueLayout.ADDRESS, ValueLayout.JAVA_LONG,
                        ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));

        try (Arena arena = Arena.ofConfined()) {
            MemorySegment s = arena.allocateFrom("Hello, FFM");
            System.out.println("strlen(\"Hello, FFM\") = " + (long) strlen.invokeExact(s));

            // Turn the Java method into a C function pointer (an upcall stub)
            ValueLayout.OfInt intLayout = ValueLayout.JAVA_INT;
            FunctionDescriptor cmpDesc = FunctionDescriptor.of(ValueLayout.JAVA_INT,
                    ValueLayout.ADDRESS.withTargetLayout(intLayout),
                    ValueLayout.ADDRESS.withTargetLayout(intLayout));
            MethodHandle target = MethodHandles.lookup().findStatic(CallC.class, "compareInts",
                    MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class));
            MemorySegment cmp = LINKER.upcallStub(target, cmpDesc, arena);

            int[] data = {42, 7, 19, 3, 88, 1};
            MemorySegment array = arena.allocateFrom(ValueLayout.JAVA_INT, data);
            qsort.invokeExact(array, (long) data.length, intLayout.byteSize(), cmp);
            int[] sorted = array.toArray(ValueLayout.JAVA_INT);
            System.out.println("qsort with a Java comparator: " + Arrays.toString(sorted));
        }
    }
}

Output:

Output
strlen("Hello, FFM") = 10
qsort with a Java comparator: [1, 3, 7, 19, 42, 88]

Native calls are restricted methods: a wrong function descriptor can crash the JVM, which the API cannot check. Two things follow from that:

  • javac reports a [restricted] warning for each such call with -Xlint; the program suppresses it with @SuppressWarnings("restricted").
  • At run time the JVM requires native access to be granted. The program was run with --enable-native-access=ALL-UNNAMED. Without that flag, JDK 25 still runs it, but prints:
Output
WARNING: A restricted method in java.lang.foreign.Linker has been called
WARNING: java.lang.foreign.Linker::downcallHandle has been called by CallC in an unnamed module (file:.../)
WARNING: Use --enable-native-access=ALL-UNNAMED to avoid a warning for callers in this module
WARNING: Restricted methods will be blocked in a future release unless native access is enabled

The class-path location in the second line is shortened here. For real libraries, the jextract tool generates these handles and layouts from a C header file, so you do not write descriptors by hand.

errno and variadic functions

Two features of C need extra options on the downcall. A C function reports many errors through errno, which the JVM itself may overwrite before Java code can read it, so the linker must capture it right after the call. And functions like printf take a variable number of arguments, which are passed differently at the machine level. The program opens a file that does not exist and formats a number with snprintf.

Java
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemoryLayout.PathElement;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.StructLayout;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;

// Linux and macOS: calls open() and snprintf() from the C library
public class ErrnoAndVarargs {

    static final Linker LINKER = Linker.nativeLinker();

    @SuppressWarnings("restricted")
    public static void main(String[] args) throws Throwable {
        // int open(const char *path, int flags), with errno captured right after the call
        Linker.Option errno = Linker.Option.captureCallState("errno");
        StructLayout stateLayout = Linker.Option.captureStateLayout();
        VarHandle errnoHandle = stateLayout.varHandle(PathElement.groupElement("errno"));
        MethodHandle open = LINKER.downcallHandle(
                LINKER.defaultLookup().find("open").orElseThrow(),
                FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS,
                        ValueLayout.JAVA_INT), errno);

        // int snprintf(char *buf, size_t n, const char *fmt, ...): variadic after arg 3
        MethodHandle snprintf = LINKER.downcallHandle(
                LINKER.defaultLookup().find("snprintf").orElseThrow(),
                FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS,
                        ValueLayout.JAVA_LONG, ValueLayout.ADDRESS, ValueLayout.JAVA_INT,
                        ValueLayout.JAVA_DOUBLE),
                Linker.Option.firstVariadicArg(3));

        try (Arena arena = Arena.ofConfined()) {
            MemorySegment state = arena.allocate(stateLayout);
            int fd = (int) open.invokeExact(state, arena.allocateFrom("/no/such/file"), 0);
            int code = (int) errnoHandle.get(state, 0L);
            System.out.println("open returned " + fd + ", errno " + code
                    + " (2 is ENOENT, no such file)");

            MemorySegment buf = arena.allocate(64);
            int written = (int) snprintf.invokeExact(buf, 64L,
                    arena.allocateFrom("%d items at %.2f each"), 3, 9.5);
            System.out.println("snprintf wrote " + written + " chars: " + buf.getString(0));
        }
    }
}

Output:

Output
open returned -1, errno 2 (2 is ENOENT, no such file)
snprintf wrote 20 chars: 3 items at 9.50 each
  • open returned -1, and the captured errno was 2, which is ENOENT on Linux. Linker.Option.captureCallState("errno") adds a first parameter to the method handle: a segment, laid out by captureStateLayout(), into which the value is copied.
  • Linker.Option.firstVariadicArg(3) tells the linker that arguments from index 3 on are the "..." part. The descriptor lists the types actually passed in this call, an int and a double; a different call with other types needs its own handle.
  • snprintf wrote 20 characters, "3 items at 9.50 each", into a 64-byte native buffer, which getString(0) read back up to the terminating zero.

How fast is checked off-heap access?

The program sums ten million ints stored three ways: a Java array, a direct IntBuffer, and a MemorySegment. Each runs 3 times after a warm-up round and the fastest is shown. This is a rough comparison on a 2-CPU Linux machine with JDK 25.

Java
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.function.LongSupplier;

public class AccessSpeed {

    static final int N = 10000000;

    public static void main(String[] args) {
        int[] array = new int[N];
        IntBuffer direct = ByteBuffer.allocateDirect(N * 4).order(ByteOrder.nativeOrder())
                .asIntBuffer();
        try (Arena arena = Arena.ofConfined()) {
            MemorySegment seg = arena.allocate(ValueLayout.JAVA_INT, N);
            for (int i = 0; i < N; i++) {
                array[i] = i % 100;
                direct.put(i, i % 100);
                seg.setAtIndex(ValueLayout.JAVA_INT, i, i % 100);
            }
            for (int round = 0; round < 2; round++) {          // round 0 is warm-up
                boolean print = round == 1;
                time("int[] on the heap", print, () -> {
                    long s = 0;
                    for (int i = 0; i < N; i++) {
                        s += array[i];
                    }
                    return s;
                });
                time("direct IntBuffer", print, () -> {
                    long s = 0;
                    for (int i = 0; i < N; i++) {
                        s += direct.get(i);
                    }
                    return s;
                });
                time("MemorySegment", print, () -> {
                    long s = 0;
                    for (long i = 0; i < N; i++) {
                        s += seg.getAtIndex(ValueLayout.JAVA_INT, i);
                    }
                    return s;
                });
            }
        }
    }

    static void time(String label, boolean print, LongSupplier work) {
        long best = Long.MAX_VALUE;
        long sum = 0;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            sum = work.getAsLong();
            best = Math.min(best, System.nanoTime() - t0);
        }
        if (print) {
            System.out.printf("%-18s sum %,d  best of 3: %5.1f ms%n", label, sum, best / 1e6);
        }
    }
}

Output:

Output
int[] on the heap  sum 495,000,000  best of 3:   2.3 ms
direct IntBuffer   sum 495,000,000  best of 3:   2.3 ms
MemorySegment      sum 495,000,000  best of 3:   2.3 ms

All three took about the same time. In a simple loop the JIT hoists the bounds and liveness checks of the segment out of the loop, so reading off-heap memory through the FFM API costs no more than reading an array. The difference that matters is elsewhere: segments can be larger than 2 GB, can be freed deterministically, and can be passed to C code.

Which one to use

Choosing between FFM, buffers and JNI
NeedUse
Ordinary data structuresJava objects and arrays on the heap
Large off-heap buffer with deterministic releaseArena.ofConfined() or ofShared() with MemorySegment
Memory-mapped file above 2 GBFileChannel.map(mode, offset, size, arena)
Binary data with a fixed structureMemoryLayout and VarHandles
Calling a C libraryLinker downcalls, generated by jextract for large APIs
C code that calls back into JavaLinker.upcallStub
APIs that require ByteBuffer (NIO channels, older libraries)ByteBuffer, or segment.asByteBuffer()
Code that must run on Java 21 or olderJNI or ByteBuffer; FFM is a preview there

For the buffer classes, see ByteBuffer; for the handles used to access layouts, see VarHandle.