JNI and foreign function interface
What you will learn
JNI connects Java methods to native implementations. The Foreign Function & Memory (FFM) API offers Java abstractions for native memory and foreign calls. Native code shares the process and can violate Java safety guarantees.
- Explain ABI, ownership and native-access permissions.
- Distinguish JNI and stable FFM version requirements.
- Use a bounded Java memory buffer and review a native lifetime example.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Use only trusted local classes and fixed synthetic data. For module commands use the companion lab described below. Never load unknown native code or attach to another process. The runner enforces a process deadline.
Distinguish heap and direct buffers
public class Main {
public static void main(String[] args) throws Exception { var heap = java.nio.ByteBuffer.allocate(4); var direct = java.nio.ByteBuffer.allocateDirect(4); System.out.println(heap.isDirect()); System.out.println(direct.isDirect()); }}Expected output:
falsetrueBoth buffers expose bounded Java operations. Direct storage may be outside the heap; this does not demonstrate foreign calls.
JNI boundary
A native method has a declaration such as static native int sample(); with no Java body. javac -h generates a C header with the JNI signature. A matching trusted library can be loaded explicitly and invoked. JNI uses JNIEnv, local/global references, thread attachment rules and explicit ownership. Never use arbitrary libraries or paths derived from untrusted input. Native bugs can corrupt memory or crash the VM. The companion lab includes a fixed C function returning 42 and a Java declaration; it is compiled and loaded only by the owned local test. No native calls accepting pointers or user data.
FFM on Java 22 and newer
Java 21 FFM is preview and differs from the final API (Java 22). Java 25 source-reviewed example, not executed here:
import java.lang.foreign.Arena;import java.lang.foreign.MemorySegment;import java.lang.foreign.ValueLayout;class ForeignSample { public static void main(String[] args) { try (Arena arena = Arena.ofConfined()) { MemorySegment cell = arena.allocate(ValueLayout.JAVA_INT); cell.set(ValueLayout.JAVA_INT, 0, 42); System.out.println(cell.get(ValueLayout.JAVA_INT, 0)); } }}Expected on Java 25: 42. A confined arena restricts access to its owner thread and releases allocated native storage when closed. A segment obtained from it becomes invalid after closure. Layout, alignment, byte order, bounds and lifetime matter. Linker and FunctionDescriptor describe native calling conventions and signatures; the ABI must match exactly. Pointer lifetimes from native code require independent ownership knowledge.
Version and permission policy
Java 24 introduced JNI native-access warnings and aligned restrictions with FFM. In Java 25 unauthorized restricted operations can warn by default; policy may deny them. Grant native access only to a reviewed named module when required using the documented --enable-native-access=module.name; do not blanket-enable it for unrelated code. The local JNI fixture runs on Java 21, not Java 25. Direct ByteBuffer offers a Java 21 comparison for bounded access, not a replacement for FFM lifetime control. Vector API is incubating in JDK 25; it is not stable Java SE and is not required for this lesson.
Write with an explicit byte order
public class Main {
public static void main(String[] args) throws Exception { var b = java.nio.ByteBuffer.allocateDirect(4).order(java.nio.ByteOrder.BIG_ENDIAN); b.putInt(0, 42); System.out.println(b.getInt(0)); System.out.println(b.get(3)); }}Expected output:
4242An explicit byte order makes the final byte predictable. Absolute access uses an index rather than advancing position.
Check a native declaration without loading it
public class Main { static native int sample(); public static void main(String[] args) throws Exception { var method = Main.class.getDeclaredMethod("sample"); System.out.println(java.lang.reflect.Modifier.isNative(method.getModifiers())); System.out.println(method.getReturnType() == int.class); }}Expected output:
truetrueReflection inspects the declaration only. Calling it without a matching linked implementation would fail.
Common mistakes
Do not infer pointer size from Java int, assume a direct buffer has an explicit close, pass unchecked offsets, return a segment from a closed arena, or load a library from an arbitrary path.
Practice
Allocate an eight-byte direct buffer, set little-endian order, write long 256 at offset zero, and print the value and the unsigned second byte. Explain why the FFM arena version would need a later JDK.
Expected output:
2561Compare your answer with the manual practice criteria.
Official reading: JNI · FFM · Arena · Native access. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JNI and foreign function interface — knowledge check
Original module, packaging and native-interface questions.
What can native code do inside a JVM process?
When did the FFM API become final?
What happens to a confined arena allocation when closed?
What must match for a foreign call?
Which is a suitable native-access policy?