Core Java

Foreign Function and Memory API vs JNI vs jextract: Safety, Speed and a Real Example

If you have ever written a JNI wrapper, you remember the ritual: a header, a C file, a compiler, and a crash that tells you nothing. The Foreign Function and Memory API (FFM) promises the same result from plain Java. I wanted to see how much of that promise holds up, so I called a real C library, zlib, from both APIs and measured what happened. Before that, though, let me pin down where each tool stands today.

Where Each Tool Stands Right Now

FFM was finalized in Java 22 through JEP 454. According to Inside Java, JDK 25 is the first release that carries it together with broad long-term support. JNI, meanwhile, is not going away, but it is being treated more strictly.

Since JDK 24, JEP 472 makes JNI and FFM behave the same way: both are restricted, and both print a warning unless you pass --enable-native-access. Oracle’s JDK 26 documentation still lists warn as the default and says deny will become the default in a future release. I found no evidence that this has changed since.

ToolStatusPart of the JDK?
FFM APIFinal since Java 22Yes, in java.lang.foreign
JNISupported, but restricted with warnings since Java 24Yes
jextractEarly-access builds onlyNo, separate download

About jextract: the download page labels it early access. The newest build I could find was based on JDK 25 and dated 25 November 2025. A newer one may exist by the time you read this, so check the page yourself.

The Test Case: zlib’s crc32

The FFM version

I chose the crc32 function from zlib because it is small, real and installed almost everywhere. The code below is the whole FFM program. It needs JDK 22 or newer and a Linux system with libz.so.1, and I ran it exactly as written.

cat > FfmCrc.java <<'EOF'
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import static java.lang.foreign.ValueLayout.*;
import static java.nio.charset.StandardCharsets.UTF_8;

public class FfmCrc {
    public static void main(String[] args) throws Throwable {
        Linker linker = Linker.nativeLinker();
        try (Arena arena = Arena.ofConfined()) {
            SymbolLookup zlib = SymbolLookup.libraryLookup("libz.so.1", arena);
            MethodHandle crc32 = linker.downcallHandle(
                zlib.find("crc32").orElseThrow(),
                FunctionDescriptor.of(JAVA_LONG, JAVA_LONG, ADDRESS, JAVA_INT));
            byte[] text = "hello world".getBytes(UTF_8);
            MemorySegment data = arena.allocateFrom(JAVA_BYTE, text);
            long result = (long) crc32.invokeExact(0L, data, text.length);
            System.out.println(result);
        }
    }
}
EOF
javac FfmCrc.java
java --enable-native-access=ALL-UNNAMED FfmCrc

It prints 222957957, which is the correct CRC-32 of “hello world”. Notice that there is no C code, no header and no build step beyond javac.

The JNI version

The same job through JNI needs a Java class, a generated header, a C file and a compiler run. As a result, you maintain two languages and a native build.

mkdir jni && cd jni
cat > CrcJni.java <<'EOF'
import static java.nio.charset.StandardCharsets.UTF_8;

public class CrcJni {
    static { System.loadLibrary("crcjni"); }
    static native long crc32(byte[] data);

    public static void main(String[] args) {
        System.out.println(crc32("hello world".getBytes(UTF_8)));
    }
}
EOF
javac -h . CrcJni.java
cat > crcjni.c <<'EOF'
#include <jni.h>
#include <zlib.h>
#include "CrcJni.h"

JNIEXPORT jlong JNICALL Java_CrcJni_crc32(JNIEnv *env, jclass cls, jbyteArray data) {
    jsize len = (*env)->GetArrayLength(env, data);
    jbyte *buf = (*env)->GetPrimitiveArrayCritical(env, data, NULL);
    if (buf == NULL) return 0;
    uLong crc = crc32(crc32(0L, Z_NULL, 0), (const Bytef *) buf, (uInt) len);
    (*env)->ReleasePrimitiveArrayCritical(env, data, buf, JNI_ABORT);
    return (jlong) crc;
}
EOF
JH=$(dirname $(dirname $(readlink -f $(which javac))))
gcc -shared -fPIC -I$JH/include -I$JH/include/linux crcjni.c -o libcrcjni.so -lz
java -Djava.library.path=. --enable-native-access=ALL-UNNAMED CrcJni
java --enable-native-access=ALL-UNNAMED FfmCrc

This prints the same 222957957. It needs the zlib development headers (the zlib1g-dev package on Ubuntu) plus a C compiler.

And jextract?

For one function, jextract is overkill. Its value shows up when a header has dozens of functions and structs. According to a Foojay tutorial, you point it at a header, for example with jextract --output generated -t org.zlib -l z /usr/include/zlib.h, and it writes Java source for the downcall handles and layouts. That tutorial also notes it understands C only, so C++ libraries need a C interface. I could not download jextract in my sandbox, so I did not run that command myself.

Safety: What Happens When You Get It Wrong

I triggered four mistakes on purpose and recorded the result on OpenJDK 25.

MistakeWhat happened
FFM: read past the end of a 64-byte segmentIndexOutOfBoundsException
FFM: use a segment after its arena was closedIllegalStateException: Already closed
JNI: pass the invalid address 1 to native codeJVM crash with SIGSEGV
FFM: build a segment at address 1 with reinterpret and pass it to native codeJVM crash with SIGSEGV

The first two rows are where FFM clearly wins. The API checks bounds and lifetime in Java, so ordinary mistakes become exceptions you can read. However, the last row matters just as much. Once you override the checks with reinterpret, or hand a bad pointer to C, you are back in crash territory. Oracle’s documentation says exactly that: the restricted methods can cause a JVM crash or silent memory corruption when used incorrectly.

Speed: What I Measured

The setup

I used OpenJDK 25.0.5.1 and Ubuntu’s zlib 1.3 build on a single-core sandbox. Timing came from a hand-written loop with warm-up, not from JMH, and every figure below is the median of five complete runs. In the JNI shim I passed a raw address, which avoids copying and gives JNI its best case.

The cost of the call itself

To isolate the crossing between Java and C, I called libc’s abs, a function that does almost no work.

median of five runs, one million calls per timing, nanoseconds per call, lower is better. FFM ranged 9.6 to 12.7 ns and JNI 12.0 to 15.8 ns.

Both were cheap, and FFM was slightly ahead. Still, a difference of two nanoseconds will not matter in most programs.

A real function on real data

Next came zlib’s crc32 on a 64-byte buffer. I added a fourth bar for java.util.zip.CRC32, because it is the pure-Java alternative.

median of five runs, nanoseconds per call on a 64-byte buffer, lower is better. FFM ranged 110.9 to 118.5 ns, JNI 107.0 to 117.6 ns.
Approach64 bytes (ns)64 KB (ns)
java.util.zip.CRC326.7922
FFM downcall116.214,112
FFM with the critical linker option109.214,618
JNI109.813,804

Two conclusions follow. First, FFM and JNI landed within a few percent of each other, and their ranges overlap, so I would call this a tie rather than a win for either. Second, the JDK’s own CRC32 was roughly 15 to 16 times faster than calling zlib. In other words, going native only pays off when the JDK has nothing equivalent.

Keep the limits in mind. This was one machine, and I did not test heap arrays or callbacks from C into Java. Treat the numbers as a method you can repeat, not as a general verdict.

jextract in Practice

Hand-writing a descriptor for one function is fine. For a library with a large header, it quickly becomes tedious, and that is exactly what jextract removes. It generates the code you would otherwise type, so you review it instead of writing it. Older early-access notes also listed gaps such as function-like macros and bitfield accessors, so check the current notes before you rely on a specific header.

Quick decision guide

  • New native calls on Java 22 or newer: start with FFM, ideally on the Java 25 LTS.
  • A handful of functions: write the downcall by hand, as in the example above.
  • A big C header: try jextract, and review the generated code.
  • Existing JNI code: it keeps working, but add --enable-native-access and use the jnativescan tool from JEP 472 to find where you rely on it.

What We Have Learned

FFM has been final since Java 22 and is available on the Java 25 LTS, while jextract is still an early-access tool outside the JDK. Since Java 24, both JNI and FFM print warnings unless native access is enabled, and a stricter default is planned for a later release. In my zlib test, FFM needed no C code and turned bounds and lifetime mistakes into exceptions, whereas a bad pointer crashed the JVM in both APIs. Call overhead was about 10 ns for FFM and 12 ns for JNI, and the zlib calls performed about the same either way. Pure Java’s CRC32 beat both, so check the JDK before going native. Rerun the measurements on your own hardware.

Eleftheria Drosopoulou

Eleftheria is an Experienced Business Analyst with a robust background in the computer software industry. Proficient in Computer Software Training, Digital Marketing, HTML Scripting, and Microsoft Office, they bring a wealth of technical skills to the table. Additionally, she has a love for writing articles on various tech subjects, showcasing a talent for translating complex concepts into accessible content.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button