Skip to content
Tutorials Center
My learning

Topics

Lesson 168 of 201 ยท JVM and Advanced Topics

Native Code: JNI and the Foreign Function API

Call C libraries from Java. Compare the old JNI with the modern Foreign Function and Memory API: Linker, Arena, MemorySegment, downcalls and upcalls.

Most Java code never leaves the JVM. But sometimes you must: an operating-system feature the JDK doesn't expose, a mature C library for compression, imaging or cryptography, a GPU or hardware driver, or a performance-critical routine already written in C. Java has two ways to cross that border: JNI (the Java Native Interface), available since Java 1.1, and the Foreign Function & Memory API (FFM, developed under the name Project Panama), which became a standard, final API in Java 22.

This lesson shows both, but spends most of its time on FFM, because it is the one you should choose for new code. It is plain Java: no C glue, no header files and no extra compile step. You'll also learn the safety rules that matter: native code can crash the whole JVM, so the boundary deserves respect. The JVM background is in JVM Architecture.

The old way: JNI

With JNI you declare a method as native in Java, write the implementation in C, compile it into a shared library and load that library at runtime. Here is the Java side:

Java
public class Calc {
    static {
        System.loadLibrary("calc");      // finds libcalc.so, calc.dll or libcalc.dylib
    }

    public static native int add(int a, int b);

    public static void main(String[] args) {
        System.out.println(Calc.add(2, 3));
    }
}

Then javac -h . Calc.java compiles the class and generates a C header, Calc.h, containing the exact function signature JNI expects. You implement it in C:

C
#include <jni.h>
#include "Calc.h"

JNIEXPORT jint JNICALL Java_Calc_add(JNIEnv *env, jclass cls, jint a, jint b) {
    return a + b;
}

Finally you compile that file to a shared library with a C compiler (for example gcc -shared -fPIC -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/linux" -o libcalc.so calc.c), put it on java.library.path and run the program.

That is a lot of machinery for adding two numbers, and it gets worse. Calling an existing C library (say, one with a function called strlen) means writing a C wrapper for every function you need. Strings, arrays and objects must be converted with JNIEnv helper calls, and mistakes (forgotten references, wrong signatures) crash the JVM with no helpful message. The name Java_Calc_add is also fragile: rename the class and the link breaks at runtime. JNI still works, and lots of old libraries use it, but you rarely have a reason to start a new JNI project today.

The modern way: the Foreign Function & Memory API

FFM lets Java code do three things directly:

  1. Find a function in a native library (or the C standard library).
  2. Call it through a MethodHandle, with Java doing the type conversion.
  3. Manage native memory safely, with bounds checks and a lifetime.

The main types live in java.lang.foreign:

Type Role
Linker Connects Java and native code; creates downcall and upcall handles
SymbolLookup Finds a function's address by name (defaultLookup() covers the C library)
FunctionDescriptor Describes a C function: the return layout and the parameter layouts
ValueLayout Describes primitive types (JAVA_INT, JAVA_LONG, JAVA_DOUBLE, ADDRESS, ...)
MemorySegment A contiguous region of memory, with a size, bounds checks and a lifetime
Arena Owns segments; closing it frees the native memory
flowchart LR
    J["Java code"] -->|"MethodHandle (downcall)"| L["Linker"]
    L --> N["Native function<br/>(strlen, qsort, your library)"]
    N -->|"upcall stub"| J
    J --> A["Arena"]
    A --> M["MemorySegment<br/>(native memory)"]
    N --> M

A downcall goes from Java into C. An upcall is a Java method that C code calls back. Both exchange data through memory segments owned by an arena.

Your first downcall

The C library's strlen takes a pointer to a zero-terminated string and returns its length as size_t, which is 64 bits on today's 64-bit platforms (so JAVA_LONG). Calling it from Java takes five steps: get the linker, look up the symbol, describe the signature, allocate the string in native memory and invoke.

Java Calling strlen from the C library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at what each line does. FunctionDescriptor.of(returnLayout, paramLayouts...) is the Java picture of size_t strlen(const char *s). allocateFrom(String) copies the text into native memory as UTF-8 plus a terminating zero byte. invokeExact calls the function, and the cast (long) must match the descriptor exactly: this is a MethodHandle rule, and a mismatch throws WrongMethodTypeException. When the try block ends, the arena closes and the native string is freed.

On the first restricted call, Java 25 prints a warning to standard error that says native access is not enabled for your code. That is expected in our sandbox. In a real project, you grant access explicitly with --enable-native-access=ALL-UNNAMED (for classpath code) or --enable-native-access=my.module (for modules). Native calls are "restricted" on purpose: a wrong descriptor can crash the JVM, so the platform makes you opt in.

Memory: segments, layouts and arenas

Java arrays live on the garbage-collected heap, so the collector can move them, and C cannot hold a pointer into them. FFM instead gives you off-heap memory as a MemorySegment. Every access is bounds-checked and checked against the segment's lifetime, which is the key safety improvement over C and over the older sun.misc.Unsafe.

The arena decides the lifetime:

  • Arena.ofConfined() is used by one thread and closed explicitly (usually with try-with-resources).
  • Arena.ofShared() can be used by several threads and closed explicitly.
  • Arena.ofAuto() frees memory when the segment becomes unreachable (the garbage collector decides when).
  • Arena.global() never frees.

Structs are described with MemoryLayout.structLayout, and a VarHandle (or in newer code, simple get/set with offsets) reads the fields. This example builds a C-style struct { int id; double score; } in native memory, and also shows the two protections: the bounds check and the lifetime check.

Java Native memory with layouts and safety checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In C, both mistakes would silently corrupt memory or crash. Here they are ordinary exceptions. Remember the padding: a C compiler puts 4 bytes between the int and the double so the double is aligned on 8 bytes, and the layout must say so explicitly.

Upcalls: C calling Java

Many C APIs take a callback function pointer. The classic example is qsort, which sorts an array and asks you to compare two elements. With FFM you turn a Java method into a function pointer with linker.upcallStub. Below, qsort from the C library sorts five native integers, and every comparison runs your Java method:

Java Sorting with qsort and a Java comparator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The comparator receives raw pointers as zero-length segments, so it calls reinterpret(4) to say "this address points to 4 valid bytes". That call is itself restricted, because the JVM can't verify your claim. The stub is tied to the arena, so it lives exactly as long as the native code might call it. It is an excellent example of the FFM design: the unsafe step is small, explicit and visible.

Calling your own library

The default lookup only finds the C standard library. To call another library, load it:

Java
// Linux/macOS/Windows: by library name, found through the OS search path
SymbolLookup lookup = SymbolLookup.libraryLookup("libcalc.so", arena);
MethodHandle add = linker.downcallHandle(
    lookup.find("add").orElseThrow(),
    FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT));
int sum = (int) add.invokeExact(2, 3);

Notice that the C code is ordinary C: int add(int a, int b) in a plain shared library, with no JNIEnv, no jint, no generated header. That is why FFM is attractive for wrapping existing libraries. For large C headers, the JDK includes a tool, jextract, (downloaded separately) that reads a header file and generates all the Java descriptors and handles for you. Our sandbox can't build or load custom shared libraries, so the snippet above is read-only.

Safety and design advice

  • Native code can crash the JVM. A wrong descriptor, a dangling pointer or a C bug brings down the whole process, with no Java exception. Keep the native surface small and test it hard.
  • Match types exactly. int is JAVA_INT, C long is 64 bits on Linux/macOS but 32 bits on Windows, and size_t follows the platform's pointer size. Check the library's header, not your memory.
  • Mind lifetimes. Free what you allocate: use try-with-resources on arenas. Never keep a pointer after the arena closed.
  • Cache MethodHandles. Creating a handle is slow; calling one is fast. Store it in a static final field.
  • Wrap it. Hide FFM details behind a small Java class with a normal API, validate arguments there, and the rest of the code base never touches native types. See Reflection for the MethodHandle and Lookup ideas it builds on.
  • Check whether you need native code at all. The JIT compiler is very good (see Performance), and a pure-Java library or a separate process is often safer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about JNI is correct?

    With JNI you declare native methods, generate a header with javac -h, implement them in C using jni.h and load the library. FFM is the approach that avoids that glue.
  2. 2. What does FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS) describe?

    The first argument is the return layout and the rest are parameter layouts. This matches size_t strlen(const char *) on a 64-bit platform.
  3. 3. What happens when you read from a MemorySegment after its confined Arena was closed?

    Segments carry a lifetime that is checked on every access, so use after free becomes an exception instead of undefined behavior.
  4. 4. What is an upcall stub used for?

    Linker.upcallStub turns a Java MethodHandle into a native function pointer, for callback parameters like the comparator in qsort.
  5. 5. Why does FFM make you opt in with --enable-native-access?

    Restricted methods are unsafe in the sense that the JVM cannot verify your declarations. The flag makes the decision explicit for the whole application.

Summary

  • JNI needs native methods, a generated header, C glue code and a shared library. It still works but is cumbersome and error-prone.
  • The Foreign Function & Memory API (final in Java 22) calls native code with plain Java: Linker, SymbolLookup, FunctionDescriptor and MethodHandles.
  • MemorySegments and Arenas give safe off-heap memory with bounds and lifetime checks; layouts describe C structs including padding.
  • upcallStub turns a Java method into a C callback pointer, as in qsort.
  • Native calls are restricted: enable them with --enable-native-access, keep the native surface small and wrap it in a normal Java API.
  • jextract generates bindings from C headers for large libraries.

Next: JVM Options and GC Tuning, where you control the JVM that runs all this code.