Sub topic 1
Why the FFM API and how it differs from JNI
Prerequisites
This chapter assumes you have:
- Solid Java fundamentals, including classes, static methods and try-with-resources.
- Basic familiarity with
java.lang.invoke.MethodHandle. - Basic C knowledge: pointers, structs, function signatures and null-terminated strings.
- A JDK 22 or later installation.
The problem with JNI
The Java Native Interface (JNI) has been the standard way to call C from Java since Java 1.1. It works, but it asks a lot of you:
- Declare a
nativemethod in a Java class. - Generate a C header with
javac -h. - Write C "glue" code that converts between JNI types (
jstring,jintArray) and plain C types. - Compile that glue into a shared library for every platform you support.
- Load it with
System.loadLibrary.
Even for one call to an existing library, you must write and ship C code. JNI also pushes memory management onto you. Native memory is not covered by the garbage collector. A forgotten free leaks memory, and a use-after-free crashes the JVM. Direct ByteBuffers are limited to 2 GB and are freed only when the garbage collector decides to.
What the FFM API changes
The Foreign Function and Memory (FFM) API lives in the java.lang.foreign package. It became final in Java 22 (JEP 454). It lets you do the same work in pure Java:
- Memory access. A
MemorySegmentis a bounded view of native memory. Every access is checked against its size. - Lifetime control. An
Arenadecides when the memory behind its segments is freed. - Calling C. A
Linkerturns a native symbol and aFunctionDescriptorinto aMethodHandle. You then call that handle like any other.
Here is the whole flow in one picture.
A first look
You will build this up piece by piece in later chapters. For now, notice that it is one Java file and no C.
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 code is written for Java 22. In Java 23 and later, allocateUtf8String is renamed allocateFrom. Run it with --enable-native-access=ALL-UNNAMED to avoid a warning.
When the try block ends, the arena closes and the string memory is freed. You wrote no free call.
JNI and FFM side by side
| Concern | JNI | FFM API |
|---|---|---|
| Glue code | C code required | None |
| Build | Native compile per platform | Plain Java build |
| Memory lifetime | Manual, or GC-tied for `ByteBuffer` | Explicit `Arena` scopes |
| Bounds checking | None in native code | Checked on every segment access |
| Callbacks into Java | Complex, via `JNIEnv` | Upcall stubs |
| Describing C types | Hand-written conversions | Layouts such as `ValueLayout` and `StructLayout` |
When to choose which
Choose FFM for new code that calls existing C libraries, where you want to avoid building native glue. Existing JNI code keeps working, so there is no urgency to migrate it. JNI is also still needed when you must target a JDK older than 22. If you maintain a large C API, the jextract tool can generate FFM bindings from its header, which a later chapter covers.
Exercise
Name two things you must do in JNI that you do not need to do with the FFM API when calling an existing C library function.
Show answer
Any two of these: write C glue code, generate a header with javac -h, compile a shared library per platform, call System.loadLibrary. With FFM you look up the symbol, describe its signature, and call the resulting MethodHandle from Java.
Exercise
In the strlen example, what frees the memory that holds the string?
Show answer
The Arena. Closing it at the end of the try-with-resources block frees every segment it allocated.