Sub topic 1
Why the FFM API and how it differs from JNI
Prerequisites
This chapter assumes you already have the following:
- Solid Java fundamentals: classes, static methods, and try-with-resources.
- Basic familiarity with
java.lang.invoke.MethodHandle, at least that you can call one withinvokeorinvokeExact. - Basic C knowledge: pointers, structs, function signatures, and null-terminated strings.
- A JDK 22 or later installation. The
java.lang.foreignpackage was final in Java 22 (JEP 454). Earlier releases (19 to 21) shipped it as a preview that needed--enable-preview.
This chapter gives the big picture. Later chapters cover each piece in detail.
The problem: Java needs to reach native code
Java programs sometimes need things the JVM does not provide. Examples are an operating system call, a C library such as SQLite or zlib, or a block of memory that the garbage collector must not move or manage. For about 25 years the standard answer was the Java Native Interface (JNI).
JNI works, but it has costs that grow with every library you wrap. The Foreign Function and Memory (FFM) API removes most of them. It does so in plain Java, with no C code of your own.
How JNI works and where it hurts
To call C's strlen through JNI, you write a Java class with a native method.
public class NativeStrlen {
static {
System.loadLibrary("strlenjni");
}
public static native long strlen(String s);
}Then you generate a C header with javac -h. Next you write C glue code that follows the generated name and signature.
#include <jni.h>
#include <string.h>
#include "NativeStrlen.h"
JNIEXPORT jlong JNICALL Java_NativeStrlen_strlen(JNIEnv *env, jclass cls, jstring s) {
const char *utf = (*env)->GetStringUTFChars(env, s, NULL);
if (utf == NULL) {
return 0;
}
jlong n = (jlong) strlen(utf);
(*env)->ReleaseStringUTFChars(env, s, utf);
return n;
}Finally, you compile that glue into a shared library for each platform you support. The pain points are:
- Two languages and two toolchains. Every wrapped function needs hand-written C and a C compiler on the build machine, for each target operating system and CPU.
- Glue code you must keep in sync. The C function name encodes the Java package, class, and method. If you rename the Java method and forget the C side, the failure appears at run time as an
UnsatisfiedLinkError. - No help with memory. JNI has
ByteBufferfor direct memory, but its size is limited to anint(about 2 GB). Freeing it depends on the garbage collector, so you cannot say when the memory goes away. - Crashes instead of exceptions. A wrong pointer in JNI code or a missed
ReleaseStringUTFCharscan crash or corrupt the whole JVM process. - Hard to get right with structs and callbacks. You must read struct fields by offset in C, and callbacks from C into Java need a cached
JavaVMpointer and careful thread attachment.
How the FFM API works
The FFM API moves the glue from C into Java. You describe the native function in Java objects, and the JVM generates the call machinery for you. The same strlen example becomes one Java file.
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;
public class StrlenDemo {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
MethodHandle strlen = linker.downcallHandle(
linker.defaultLookup().find("strlen").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
try (Arena arena = Arena.ofConfined()) {
MemorySegment str = arena.allocateUtf8String("Hello, FFM");
long length = (long) strlen.invokeExact(str);
System.out.println(length); // 10
}
}
}This is written for Java 22, where the method is named allocateUtf8String. Java 23 and later call it allocateFrom. Run it with:
java --enable-native-access=ALL-UNNAMED StrlenDemo.javaThere is no C file, no header, and no per-platform build. The code does four things:
Linker.nativeLinker()gets the linker for the current platform's calling convention.defaultLookup().find("strlen")finds the address of the C function in the standard libraries.FunctionDescriptorstates the C signature: returns along, takes one pointer.downcallHandlecombines the address and the descriptor into aMethodHandleyou call like any other.
The Arena owns the string's native memory. When the try block ends, the memory is freed at that exact point.
Side-by-side comparison
| Concern | JNI | FFM API |
|---|---|---|
| Glue code | Hand-written C per function | None; Java descriptors |
| Build | C compiler for each platform | Plain `javac` |
| Off-heap memory | `ByteBuffer` (int-sized) or raw C pointers | `MemorySegment` (long-sized, bounds-checked) |
| Freeing memory | Manual in C, or GC-dependent for buffers | Deterministic through `Arena` |
| Access after free | Undefined behavior, possible crash | `IllegalStateException` |
| Out-of-bounds access | Undefined behavior | `IndexOutOfBoundsException` |
| Structs | Offsets computed by hand in C | `MemoryLayout` describes them |
| Callbacks into Java | `JavaVM`, thread attachment, method IDs | Upcall stub from a `MethodHandle` |
| Native-access control | Always on | `--enable-native-access` |
The two entries on freed memory and bounds show the main design choice. Native memory is still unmanaged, but every access goes through a Java object that knows its size and whether it is still alive. Java checks each access and throws an exception instead of reading bad memory.
The main building blocks
The API is a small set of types, and each later chapter covers one or two of them.
MemorySegmentis a bounded view of a contiguous region of memory, either native or on the heap.Arenacontrols the lifetime of segments allocated from it.ValueLayoutandMemoryLayoutdescribe primitives, pointers, structs, and arrays, including sizes and alignment.SymbolLookupfinds the address of a named native function or variable.FunctionDescriptordescribes a C function's parameter and return types.Linkercreates downcall handles (Java calls C) and upcall stubs (C calls Java).
Because the descriptor is just data you build in Java, you must get it right. The JVM cannot read your C header. If the descriptor says int and the C function takes long, the call is made with the wrong argument shape and the result is undefined. This is the main safety gap that remains, and a later chapter shows how jextract generates correct descriptors from a header.
Restricted methods
Methods that can break memory safety are called restricted methods. Linker.downcallHandle is one of them. In JDK 22 and later, calling a restricted method without enabling native access prints a warning. Pass --enable-native-access=ALL-UNNAMED for code on the class path, or name your module on the module path. This is why the run command above includes the flag. Later JDK releases also warn about JNI use by default, so the two approaches are being treated more alike.
When JNI is still the right choice
The FFM API is the better default for new code, but JNI is not gone. Consider JNI or an existing wrapper when:
- You must support a JDK older than 22. The API was a preview before that, and previews are not suitable for most production libraries.
- You are implementing a native method that the C side must call by name, such as code that needs
JNIEnvfeatures like creating Java objects from C. - You already maintain a stable, tested JNI layer, and rewriting it has no benefit.
For most "call this C library from Java" tasks, FFM removes the C build and the glue.
Common errors at this stage
- Forgetting
--enable-native-access. The program still runs on JDK 22, but prints a warning on stderr. Do not ignore it in production. - Using the Java 23+ method names on Java 22 (or the reverse).
allocateUtf8StringbecameallocateFrom. A compile error about a missing method usually means a version mismatch. - Reading the memory after the arena closes. This throws
IllegalStateException. That is the intended safety net, not a bug in the API. - Casting the result of
invokeExactincorrectly.invokeExactrequires the exact types of the handle, so(long) strlen.invokeExact(str)works but(int)does not.
Exercise
A teammate says the FFM API removes the need to understand native memory safety, because Java now checks everything. Give two things the API does check and one thing it cannot check.
Show answer
It checks that an access stays inside the segment's bounds, which throws IndexOutOfBoundsException, and that the segment's arena is still open, which throws IllegalStateException. It cannot check that your FunctionDescriptor matches the real C signature, so a wrong descriptor can still produce undefined behavior or crash the JVM.
Exercise
List three steps a JNI developer does that an FFM developer does not need to do to call a C library function.
Show answer
Any three of these: generate a header with javac -h, write C glue code that uses JNIEnv, compile a shared library for each target platform, and call System.loadLibrary to load that glue library.