Sub topic 1
Why the FFM API and how it differs from JNI
The Foreign Function and Memory (FFM) API, final in Java 22, lets Java call native functions and access off-heap memory without writing JNI glue code. JNI usually requires Java declarations, generated headers, and native C or C++ implementations. FFM describes native symbols, memory, and C types directly in Java.
FFM uses MemorySegment for memory, Arena for lifetime control, MemoryLayout for data structure, and MethodHandle for native calls. These objects make boundaries and lifetimes visible in the Java code.
Prerequisites
This chapter assumes solid Java fundamentals, familiarity with MethodHandle, and basic C knowledge of pointers, structs, and primitive types. Examples use JDK 22 or later.
Memory segments: bounded views of native memory
A memory segment is a bounded view of memory. It records a starting address and a size, so an access outside its bounds fails instead of silently reading unrelated memory. A segment can refer to native memory, heap memory, or mapped files.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
public class SegmentDemo {
public static void main(String[] args) {
try (Arena arena = Arena.ofConfined()) {
MemorySegment segment = arena.allocate(8);
segment.set(ValueLayout.JAVA_INT, 0, 42);
System.out.println(segment.get(ValueLayout.JAVA_INT, 0));
}
}
}The layout passed to set and get determines the number of bytes and their interpretation. An int access uses four bytes.
Arenas: controlling when memory is freed
An arena controls the lifetime of segments. Arena.ofConfined() creates memory owned by the current thread. Closing the arena releases its memory, and later access to its segments throws IllegalStateException.
Use a confined arena for short, structured operations. Use Arena.ofShared() when several threads must access the memory. Keep an arena open for at least as long as native code might retain a pointer.
Value layouts: describing ints, longs and pointers
A value layout describes a primitive value or address at a native boundary. Common layouts include JAVA_INT, JAVA_LONG, and ADDRESS. The correct layout depends on the C type and platform ABI. For example, C long is not always the same size as Java long; do not choose layouts by name alone.
A pointer layout represents an address. If the pointer refers to a known type, attach a target layout where appropriate. Layouts therefore document both the data representation and the intended access.
Exercise
What happens when a segment is accessed after its arena is closed?
Show answer
The access fails with IllegalStateException, because the segment is no longer alive.