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.allocateDirectsun.misc.Unsafe
The Foreign Function and Memory (FFM) API in java.lang.foreign
: a contiguous region of memory, on or off the heap, with a size. Every access is checked against that size.MemorySegment : controls the lifetime of segments. Closing an arena frees all its segments at once, and any later access throws instead of reading freed memory.Arena : describes the shape of data, like a C struct, and computes sizes, offsets and alignment.MemoryLayout : turns a native function into aLinker (a downcall) and a Java method into a C function pointer (an upcall).MethodHandle
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.
| JDK | JEP | Status |
|---|---|---|
| 14 to 16 | JEP 370, 383, 393, 389 | Separate incubators for memory access and the foreign linker |
| 17, 18 | JEP 412, 419 | Combined incubator |
| 19, 20, 21 | JEP 424, 434, 442 | Preview |
| 22 | JEP 454 | Standard |
On Java 21 the same code needs --enable-previewallocateUtf8StringallocateFrom
MemorySegment and Arena
An ArenaArena.ofConfined()
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 é
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:
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
- Five ints take 20 bytes. Memory from
is zero-filled.allocate - 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.
- Reading element 5 of a 5-element segment throws
instead of reading whatever lies beyond it.IndexOutOfBoundsException stores UTF-8 bytes plus a terminating zero: 1 + 2 + 3 + 1 = 7 bytes.allocateFrom(String)- 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
, so a use-after-free bug becomes an exception instead of memory corruption.IllegalStateException
| Arena | Freed when | Threads |
|---|---|---|
Arena.ofConfined() | close() | Only the owner thread |
Arena.ofShared() | close() | Any thread |
Arena.ofAuto() | The GC finds it unreachable | Any thread |
Arena.global() | Never | Any thread |
Structured memory with layouts
Computing byte offsets by hand is error-prone. A MemoryLayoutVarHandlestruct Point { int x; int y; double weight; }
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:
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
at offset 8. Three points take 48 bytes.weight - Each handle from a sequence layout takes three coordinates: the segment, a base offset (0 here) and the element index. The handle computes
for you.base + index × 16 + field offset - The layout must match what the C side expects, including padding. If a
followed a singledouble , you would addint to keep the double 8-byte aligned, and the API rejects misaligned layouts.MemoryLayout.paddingLayout(4)
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.
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:
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
: a confined arena's segments belong to the thread that created the arena. That rule lets the JVM check liveness cheaply.WrongThreadException - With
, 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 aArena.ofShared() with atomic access modes. If the arena is closed while other threads still use it, their next access throwsVarHandle , so join the workers before closing.IllegalStateException wraps a Java array as a heap segment (MemorySegment.ofArray is false).isNative() moved its 16 bytes to native memory, and writing 50 there left the array's 5 unchanged.MemorySegment.copy
Memory-mapping a file into a segment
FileChannel.mapMemorySegmentMappedByteBuffer
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:
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.
made the file's bytes for record 1 come out asJAVA_INT_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN) , most significant byte first, regardless of the CPU's own byte order. The0 0 0 1 variant allows offsets that are not multiples of 4, which binary file formats often need.UNALIGNED wrote the changed pages back to the file before it was read withforce() . SeeFiles.readAllByteshandling large files for more on mapping.
Calling C functions
The LinkerMethodHandleFunctionDescriptor
, a simple call with a pointer argument;strlen , which needs a pointer to a comparison function.qsort turns a Java method into a C function pointer, so C code calls back into Java to compare elements.upcallStub
The array {42, 7, 19, 3, 88, 1}
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:
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
warning for each such call with[restricted] ; the program suppresses it with-Xlint .@SuppressWarnings("restricted") - At run time the JVM requires native access to be granted. The program was run with
. Without that flag, JDK 25 still runs it, but prints:--enable-native-access=ALL-UNNAMED
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
errno and variadic functions
Two features of C need extra options on the downcall. A C function reports many errors through errnoprintfsnprintf
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:
open returned -1, errno 2 (2 is ENOENT, no such file)
snprintf wrote 20 chars: 3 items at 9.50 each
returned -1, and the capturedopen was 2, which iserrno on Linux.ENOENT adds a first parameter to the method handle: a segment, laid out byLinker.Option.captureCallState("errno") , into which the value is copied.captureStateLayout() tells the linker that arguments from index 3 on are the "..." part. The descriptor lists the types actually passed in this call, anLinker.Option.firstVariadicArg(3) and aint ; a different call with other types needs its own handle.double wrote 20 characters, "3 items at 9.50 each", into a 64-byte native buffer, whichsnprintf read back up to the terminating zero.getString(0)
How fast is checked off-heap access?
The program sums ten million ints stored three ways: a Java array, a direct IntBufferMemorySegment
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:
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
| Need | Use |
|---|---|
| Ordinary data structures | Java objects and arrays on the heap |
| Large off-heap buffer with deterministic release | Arena.ofConfined()ofShared()MemorySegment |
| Memory-mapped file above 2 GB | FileChannel.map(mode, offset, size, arena) |
| Binary data with a fixed structure | MemoryLayoutVarHandle |
| Calling a C library | Linkerjextract |
| C code that calls back into Java | Linker.upcallStub |
APIs that require ByteBuffer | ByteBuffersegment.asByteBuffer() |
| Code that must run on Java 21 or older | JNI or ByteBuffer |
For the buffer classes, see