Lesson · Foreign Function & Memory API
Foreign Function & Memory Overview
11 min readForeign Function & Memory Overview
The Panama stack replaced two habits: raw addresses through sun.misc.Unsafe, and C glue written by hand for JNI. It is final since JDK 22 as java.lang.foreign, and it is built so that the dangerous parts are few, named, and visible in review. This lesson is the map: why it exists, what replaced what, how the safety model works, and how to choose between FFM, JNI, JNA and plain Java.
Why the JVM needed a new story
Calling C from Java has always meant artefacts kept in sync by hand. JNI asks for a native method declaration, a C header generated from it by javac -h, and a C implementation that calls the library you actually want. Those three pieces must agree on every platform you ship, and the API hands native code a wide door into the JVM, so a mistake in C is a crash in Java rather than an exception.
Two kinds of workaround grew on top of that. JNA and JNR wrap JNI in a dynamic bridge, so you write an interface and a mapping instead of headers, and pay a per-call cost for the translation. sun.misc.Unsafe went the other way and removed the toolchain entirely: direct memory access with no header files, unsupported and unsafe by name, and its exit has now been scheduled.
- JNI's cost is the toolchain plus language friction. There is no struct, no cheap way to hand an object across, and the calling convention cannot express anything the platform ABI does not already have.
- JNA and JNR trade a bridge for convenience. You skip the build step and pay for it per call, inside a mapping layer that is one more place to debug.
- Unsafe memory access was deprecated for removal in JDK 23 (JEP 471), prints a single warning on first use from JDK 24 by default (JEP 498), and is scheduled to throw from JDK 26 or later before the methods are removed entirely. The replacements those JEPs name are VarHandle for on-heap memory and MemorySegment for off-heap memory.
All three of those options still work, and none of them is what the platform wants you to write next. The gap they left is exactly what the Panama stack fills.
What replaced what · three habits, one boundary
final in JDK 22 (JEP 454) · java.lang.foreign in java.base
The boundary is the deliverable. A wrong descriptor or a wrong length is still undefined behaviour; what the API guarantees is that the Java-side view is bounded and that the dangerous calls are named ones a reviewer can grep for.
JNI keeps its place. Nothing here removes it: what changes from JDK 24 (JEP 472) is that loading and binding native code must be enabled explicitly, the same way a restricted FFM call must be.
The Panama stack in two halves
The Foreign Function & Memory API is not a preview: it settled in JDK 22 (JEP 454) as the java.lang.foreign package inside java.base, after incubating and then previewing between JDK 17 and JDK 21. It has two halves, and they are adoptable separately, which is why the topic is worth learning even if you never call a C function.
One half calls foreign functions, the other owns foreign memory. Every type belongs to one of them.
| Job | Types | What they own |
|---|---|---|
| describe a C function | FunctionDescriptor, MemoryLayout, ValueLayout | the signature: parameter types, return type, and the platform mapping of C scalars, which Linker.canonicalLayouts() reveals for the current platform |
| find a symbol | SymbolLookup | named addresses in a loaded library: libraryLookup, loaderLookup, and the linker's defaultLookup |
| call it | Linker.downcallHandle | a MethodHandle you invoke like any other; the JVM optimises the call down to the native target |
| be called back | Linker.upcallStub | a MemorySegment that acts as a C function pointer to one of your methods |
| own memory | Arena | the lifetime: confined to one thread, shared across threads, automatic via the garbage collector, or global |
| point at memory | MemorySegment | a bounded view: a base address plus a size, checked on every access |
- A downcall is a MethodHandle. The linker builds it from a symbol and a descriptor, and from then on it is an ordinary handle you can store, pass around, and invoke through
invokeExact. - Memory belongs to an arena, not to a long. A segment owns nothing; closing the arena invalidates every segment that came from it, all at once.
- Nothing here needs a module flag to compile. The API is in
java.base, so the import is the only thing that shows up in a build file.
Learn the halves separately. Arena plus MemorySegment replaces direct ByteBuffers and Unsafe with no native code at all, and that is the half most applications need first.
Lifetimes, bounds, and restricted methods
The promise is not that mistakes are impossible. It is that the dangerous operations are few, named in the API, and visible in review. Three mechanisms carry that promise.
Bounds are spatial and temporal. A segment knows its own size, so an access outside it throws instead of corrupting memory, and it knows its arena, so an access after the arena closes throws IllegalStateException instead of reading freed memory. That is the guarantee JEP 454 words as no use-after-free, even when memory is allocated and freed across threads.
Pointers that come back from C arrive as zero-length segments: the address is there, the size is zero, and every read fails until you attach bounds yourself with reinterpret. That method is restricted, and the wording is deliberate: this is exactly where the seatbelt comes off, because you are telling the runtime how big a region it cannot check.
| Mechanism | What it stops | Where you meet it |
|---|---|---|
| spatial bounds | reading or writing past the end of the region | IndexOutOfBoundsException on a segment access |
| temporal bounds | use after free: reading memory the arena already released | IllegalStateException from any segment of a closed arena |
| restricted methods | silently linking to native code without the application saying so | a warning on first use per module unless native access is enabled |
- Restricted methods warn by default.
reinterpret,SymbolLookup.libraryLookup,System.loadandSystem.loadLibraryare examples. From JDK 22 the FFM ones warn at most once per module; from JDK 24 (JEP 472) JNI is covered the same way, and the plan is for the warning to become an exception in a later release. - Grant native access per module:
--enable-native-access=com.acme.native, or=ALL-UNNAMEDfor everything on the class path. An executable jar can carryEnable-Native-Access: ALL-UNNAMEDin its manifest instead, which is the JDK 22 and later shortcut for the same thing. - The command line changed shape in JDK 24. Before 24, enabling native access for one module made an unlisted caller fail with
IllegalCallerException. JDK 24 relaxed that to match JNI: illegal native access warns by default under--illegal-native-access=warn, anddenyrestores the strict behaviour, which is where the default is heading. - A native frame is still a native frame. Nothing here validates the library you call. What the API guarantees is that the Java-side view of its memory is bounded, not that the C code is correct.
The arena is the API; the segment is a pointer with a seatbelt. Allocate inside a lifetime you can close, keep the segments inside it, and a whole class of bug that used to be a crash becomes an exception.
Bindings, generated or described by hand
The remaining tedium is layouts: every C struct has to be described as a MemoryLayout with the right offsets, padding and platform sizes. jextract removes most of it by reading C headers and generating Java code: layouts, downcall method handles, and constants, ready to call.
What it does not remove is judgement. Generated bindings follow the headers they were given, so a struct whose shape depends on build flags, a callback you implement yourself, or a platform where the C type mapping differs still needs a human. Linker.canonicalLayouts() is how generated code and hand-written code both ask what the current platform maps C scalars onto.
- jextract depends on the FFM API rather than being part of it, so the generated code targets a stable, standard surface and the tool carries its own version.
- The output is ordinary Java. It compiles, it can be checked in, and it can be reviewed like any other generated source, which is the property hand-written JNI glue never had.
Generated bindings turn a C header into something a reviewer can read. That is the practical difference from a .c file full of JNI calls, not the call overhead.
Choosing between the four options
Four options exist at the Java and native boundary, and the choice follows the shape of the problem rather than the age of the API.
| Option | Reach for it when | What it costs |
|---|---|---|
| Pure Java | the JDK or a well-tested library already does the job, from files and sockets to crypto and compression | occasionally the last awkward feature is one shell call away, but a native dependency is a deployment problem forever |
| FFM | off-heap memory with a lifetime you control, or a C library whose API you can describe as descriptors and layouts | you describe the signature yourself, and a wrong descriptor is undefined behaviour that nothing checks |
| JNI | native code that already exists, a C library that calls back into Java in a hot loop, or behaviour the FFM API does not model | headers and glue per platform, plus native code that can break JVM invariants |
| JNA/JNR | one or two calls into a system library, with no build step, where per-call overhead does not matter | a reflective bridge: slower per call, and a mapping layer to debug |
- Where FFM wins: large off-heap buffers without the two gigabyte
ByteBufferlimit and with deterministic release, system libraries such as libc, and any C API you can describe withFunctionDescriptorvalues. - Where JNI remains: existing native code, upcalls that must reach back into Java objects, and callback-heavy designs. JEP 454 lists re-implementing JNI as an explicit non-goal, and JNI itself is not deprecated.
- One boundary detail worth knowing: a native frame pins the carrier of a virtual thread for as long as it runs, so keep native calls off a virtual-thread hot path or hand them to a dedicated platform thread.
Choose by what crosses the boundary, not by which API is newer. Existing native code and hot callbacks keep JNI; new bindings and off-heap memory start with FFM.
Decision lab · scenario in, approach out
pick a scenario, then an approachscenario
You hold a NUL-terminated C string in off-heap memory and need its length in bytes.
A symbol lookup, a descriptor and one invokeExact
- defaultLookup finds strlen in the C library, and FunctionDescriptor.of(JAVA_LONG, ADDRESS) is the Java description of size_t strlen(const char *).
- The argument is a MemorySegment, so the base address crosses to C while the Java-side bounds stay checked when you read anything back.
What it costs: You describe the signature yourself, and a wrong descriptor is undefined behaviour that nothing verifies.
Version note: Final in JDK 22 (JEP 454). Restricted methods such as reinterpret and libraryLookup warn once per module unless native access is enabled.
the roster, for this scenario
The JDK or a Java library already solves it: no native dependency at all.
Linker downcalls and upcalls, Arena and MemorySegment for the memory.
A native method, a generated header and a C implementation, kept in sync per platform.
A reflective bridge: map the C function in Java, no build step, paid for per call.
The verdicts are authored, not measured: each pair states what crosses the boundary, who owns the lifetime, and which release made the option available.
The versions you will meet
Everything in this area is version-sensitive, so here is the timeline a JDK 21 to 25 codebase should assume, with the JEP that introduced each stage.
| Release | What changed | JEP |
|---|---|---|
| JDK 17 to 18 | the API exists as an incubator module, with --add-modules jdk.incubator.foreign in every launch command | JEP 412, JEP 419 |
| JDK 19 to 21 | preview: the shape is close to the final one and needs --enable-preview, but the preview names are not the names you use now | JEP 424, JEP 434, JEP 442 |
| JDK 22 | final: java.lang.foreign is standard in java.base; restricted methods warn once per module; Arena.ofConfined, ofShared, ofAuto and Arena.global() are the factories | JEP 454 |
| JDK 23 | sun.misc.Unsafe memory-access methods deprecated for removal, with --sun-misc-unsafe-memory-access to investigate a codebase | JEP 471 |
| JDK 24 | Unsafe memory access warns on first use by default; JNI joins the FFM API under native access restrictions, with --illegal-native-access=warn as the default mode | JEP 498, JEP 472 |
| after JDK 24 | planned: an exception instead of a warning on Unsafe memory access, and native access defaulting to deny | JEP 498, JEP 472 |
Read the JEP, not the blog post. Each one says exactly what warns, what throws, and from which release, which is the only version of the claim that survives a JDK upgrade.
FFM is not Unsafe with a badge
The tempting reading is that MemorySegment is the official version of the pointer arithmetic you already had, so the old habits carry over. They do not. A segment is valid only inside the arena that allocated it, and the API will happily hand you a zero-length segment at an address a C function returned, refusing every read until you attach bounds yourself. The habits that do carry over are the review habits: name the lifetime, keep segments inside it, and treat reinterpret, libraryLookup and loadLibrary as the lines a reviewer will look at twice. That is what the restricted-method warnings are telling you, once per module, at the exact moment someone used one.
Interview angles
What did the Panama stack actually replace?+
Three things with three different problems. The memory-access methods of sun.misc.Unsafe, deprecated for removal in JDK 23 and superseded by MemorySegment and Arena. The hand-written glue of JNI for calling C, replaced by Linker downcalls from a FunctionDescriptor. And the reflective bridge of JNA and JNR, replaced by a direct call stub the JVM can optimise.
How does the FFM API keep memory access safe?+
Every MemorySegment has spatial bounds and a temporal bound. Reading past its size throws instead of corrupting memory, and using it after the arena that allocated it is closed throws IllegalStateException instead of reading freed memory. An address from C arrives as a zero-length segment, so it cannot be dereferenced until you attach bounds with the restricted reinterpret method.
What is a restricted method, and what does --enable-native-access do?+
It is a method whose use can compromise the integrity of the platform, such as libraryLookup, reinterpret, System.load, or binding a native method. From JDK 22 the FFM ones warn at most once per module unless the module was granted native access on the command line; JDK 24 (JEP 472) applies the same treatment to JNI, and the warning becomes an exception in a later release.
Common misconception: That the warning means something is broken. It means the application never said out loud that it intends to link native code, which is exactly the thing the flag records.
When would you still choose JNI over FFM?+
When native code already exists and works, when a C library calls back into Java in a hot loop, or when the interaction needs behaviour the FFM API does not model. JEP 454 makes re-implementing JNI an explicit non-goal, and JNI is supported, not deprecated.
What is jextract for, and what does it not solve?+
It reads C headers and generates Java source that describes layouts and downcall handles, which removes most of the struct-description work. It does not solve semantics: a struct whose layout depends on build flags, your own upcall implementations, and platform C type differences still need attention.