On this page
- Java & C Native Bridge (FFM API & JNI)
- Overview
- FFM API vs. JNI
- Approach 1: Modern FFM API (java.lang.foreign, JDK 22+)
- Step 1: Compile a Pure C Shared Library
- Step 2: Call It Directly from Pure Java (Zero C Glue)
- Upcalls (Passing Java Callbacks to C)
- Approach 2: Classic JNI (Java 21 LTS & Legacy Bridges)
- Safety Checklist Across Both Bridges
Java & C Native Bridge (FFM API & JNI)
Prev: Rust & Python (PyO3 + Maturin) | Up: interop | Next: index
Rel: java, c, OpenJDK Distributions & Toolchain, C Compilation & Internals, AutoCloseable, try-with-resources
Ref: OpenJDK JEP 454 — Foreign Function & Memory API | JNI Specification (Java 21)
Tags: #public #prog #interop #ffi #java #c #openjdk #tier/specialized
Overview
Java can invoke native C shared libraries (.dylib on macOS, .so on Linux, .dll on Windows) through two official OpenJDK mechanisms:
- Foreign Function & Memory (FFM) API (
java.lang.foreign, finalized in Java 22 via JEP 454 ) — The modern, pure-Java approach. No C wrapper glue code, deterministic off-heap memory lifetimes viaArena, and HotSpot JIT inlining of downcalls. - Java Native Interface (JNI) — The classic C-glue approach available in all Java versions (including Java 21 LTS and earlier), required when calling legacy JNI libraries or when C code must directly manipulate Java objects and fields.
FFM API vs. JNI
| Dimension | FFM API (java.lang.foreign, JDK 22+) |
JNI (All JDKs) |
|---|---|---|
| C glue code required? | No — call C ABI symbols directly from Java | Yes — must write .c wrapper with JNIEnv* |
| Memory safety | Spatial bounds checks + temporal Arena lifetimes |
Manual pointer/ref management; crashes JVM on bugs |
| Performance | Very fast; HotSpot intrinsifies MethodHandle downcalls |
Higher per-call marshalling overhead |
| Binding generation | jextract generates Java bindings from .h headers |
javac -h generates C headers from native methods |
| Enable flag | --enable-native-access=ALL-UNNAMED (or module name) |
Works by default (future JDKs restricting native access too) |
Approach 1: Modern FFM API (java.lang.foreign, JDK 22+)
Step 1: Compile a Pure C Shared Library
// math_native.c
#include <stddef.h>
#include <stdint.h>
int64_t sum_i32(const int32_t *data, size_t len) {
int64_t total = 0;
for (size_t i = 0; i < len; i++) {
total += data[i];
}
return total;
}
Compile to a shared library on macOS (or .so on Linux):
cc -O2 -shared -fPIC math_native.c -o libmath_native.dylib
Step 2: Call It Directly from Pure Java (Zero C Glue)
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.nio.file.Path;
public class FfmBridgeDemo {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
// Arena deterministically frees off-heap memory and unloads library on close()
try (Arena arena = Arena.ofConfined()) {
SymbolLookup lib = SymbolLookup.libraryLookup(
Path.of("libmath_native.dylib"), arena);
MemorySegment fnAddr = lib.find("sum_i32").orElseThrow();
FunctionDescriptor sig = FunctionDescriptor.of(
ValueLayout.JAVA_LONG, // int64_t return
ValueLayout.ADDRESS, // const int32_t *data
ValueLayout.JAVA_LONG // size_t len (64-bit platforms)
);
MethodHandle sumI32 = linker.downcallHandle(fnAddr, sig);
// Allocate off-heap int32_t array managed by this Arena
MemorySegment buf = arena.allocateFrom(ValueLayout.JAVA_INT, 10, 20, 30, 40);
long result = (long) sumI32.invokeExact(buf, 4L);
System.out.println("sum_i32 = " + result); // 100
}
}
}
Run with JDK 22+:
java --enable-native-access=ALL-UNNAMED FfmBridgeDemo.java
Upcalls (Passing Java Callbacks to C)
Use linker.upcallStub(methodHandle, descriptor, arena) to pass a Java method as a C function pointer (for example, a comparator for qsort).
Approach 2: Classic JNI (Java 21 LTS & Legacy Bridges)
When targeting Java 21 LTS or interoperating with existing JNI libraries:
- Declare a
nativemethod in Java:
public class NativeMath {
static {
System.loadLibrary("math_jni"); // loads libmath_jni.dylib / .so
}
public static native long sumArray(int[] values);
}
- Generate the C header:
javac -h . NativeMath.java
- Implement the JNI C wrapper:
#include "NativeMath.h"
JNIEXPORT jlong JNICALL Java_NativeMath_sumArray(JNIEnv *env, jclass cls, jintArray arr) {
jsize len = (*env)->GetArrayLength(env, arr);
jint *elems = (*env)->GetIntArrayElements(env, arr, NULL);
if (elems == NULL) return 0; // OutOfMemoryError already pending
jlong total = 0;
for (jsize i = 0; i < len; i++) {
total += elems[i];
}
(*env)->ReleaseIntArrayElements(env, arr, elems, JNI_ABORT); // read-only: skip copy-back
return total;
}
- Compile against JDK headers (
$JAVA_HOME/includeand$JAVA_HOME/include/darwinon macOS, orlinuxon Linux):
cc -O2 -shared -fPIC \
-I"$JAVA_HOME/include" -I"$JAVA_HOME/include/darwin" \
math_jni.c -o libmath_jni.dylib
java -Djava.library.path=. NativeMath
Safety Checklist Across Both Bridges
- Never leak off-heap memory: In FFM, scope allocations to
try (Arena arena = Arena.ofConfined()); in JNI, always pairGet*ElementswithRelease*Elementsand delete global refs. - Check ABI sizes: C
longis 64-bit on LP64 (macOS/Linux) and 32-bit on LLP64 (Windows); prefer fixed-width<stdint.h>types (int32_t,int64_t) in your C API. - Avoid pinning GC heaps: Keep JNI
GetPrimitiveArrayCriticalsections tiny and never call back into Java while holding a critical pointer.
Linked from
Related notes
- tuts/interop Linked here; links to this page; shared tags: #ffi, #interop, #prog
- tuts/java Linked here; links to this page; shared tags: #java, #openjdk, #prog
- tuts/c Linked here; links to this page; shared tags: #c, #prog
- tuts/java/builtins/AutoCloseable Linked here; shared tags: #java, #prog, #tier
- tuts/java/builtins/try_with_resources Linked here; shared tags: #java, #prog, #tier
- tuts/java/jvm_and_openjdk/openjdk_distributions_and_toolchain Linked here; shared tags: #java, #openjdk, #tier
- tuts/c/compilation_and_internals Linked here; shared tags: #c, #prog
- tuts/interop/rust_and_python_pyo3_maturin Linked here; shared tags: #interop, #prog
- tuts/third_party/java links to this page; shared tags: #java, #prog
- tuts/index Linked here; shared tags: #prog