On this page
  1. Java & C Native Bridge (FFM API & JNI)
  2. Overview
  3. FFM API vs. JNI
  4. Approach 1: Modern FFM API (java.lang.foreign, JDK 22+)
  5. Step 1: Compile a Pure C Shared Library
  6. Step 2: Call It Directly from Pure Java (Zero C Glue)
  7. Upcalls (Passing Java Callbacks to C)
  8. Approach 2: Classic JNI (Java 21 LTS & Legacy Bridges)
  9. 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:

  1. 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 via Arena, and HotSpot JIT inlining of downcalls.
  2. 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:

  1. Declare a native method in Java:
public class NativeMath {
    static {
        System.loadLibrary("math_jni"); // loads libmath_jni.dylib / .so
    }

    public static native long sumArray(int[] values);
}
  1. Generate the C header:
javac -h . NativeMath.java
  1. 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;
}
  1. Compile against JDK headers ($JAVA_HOME/include and $JAVA_HOME/include/darwin on macOS, or linux on 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

Linked from

Related notes