When Java must talk to a C library
A Java application may need a computation library already written in C, or data maintained outside the JVM heap. In previous chapters, objects were created, read and collected under Java platform rules. Here the boundary changes: a native function follows the machine's calling conventions, and an external memory block has a size and lifetime we must respect explicitly. The problem to solve is using that boundary without pretending that ordinary object checks automatically make native code safe.
The Foreign Function and Memory API, or FFM, has lived in the stable java.lang.foreign package since version 22 and is available in Java 25. It has two connected families: memory-segment management and linkage to external functions. Historically, Java has also used JNI, the Java Native Interface. JNI remains a valid technology for existing integrations and particular cases; FFM offers a different model, with Java APIs to describe memory, signatures and lifetime. Merely replacing a JNI call with an FFM call does not make a native library portable.
Key concept – Three levels not to confuse. A Java program may be portable at bytecode level. The FFM API is part of the platform. The C function being called remains tied to a library, operating system, architecture and ABI, meaning the set of conventions by which values pass between functions on the machine. The C contract must be known and verified; the linker cannot guess it from the function name.
Figure 28.1 shows three distinct objects: the arena governs lifetime, the segment bounds a region and the layout describes how to interpret the bytes. If the segment represents three integers, its size in bytes depends on the chosen layout. A MemorySegment can also refer to heap memory; “segment” does not always mean “off-heap”. In the example we use a native region to make the life cycle observable.
Allocating and reading with an explicit boundary
Arena.ofConfined() creates an arena accessible by the owning thread and deterministically closeable. try-with-resources closes the arena even if an internal operation throws an exception. Segments allocated by it share the arena's lifetime: after closure they can no longer be used. Arena.ofShared() allows access from multiple threads and requires more coordination discipline; Arena.ofAuto() delegates reclamation to automatic management; Arena.global() lasts for the process's whole lifetime. Choose the least extensive form covering the real need. For a buffer used by a single method, the confined arena makes the temporal boundary readable.
“Shared” describes who can access the arena, rather than guaranteeing that multiple modifications to the same segment form an atomic decision. In chapter 20A, we separated state accessibility and update protocol: the same question returns here, with segment lifetime, layout and possible native calls added. If two threads or the C library write to the same space, coordination compatible with both sides of the boundary must be defined; an AtomicInteger living elsewhere in the JVM does not protect those bytes simply by existing.
ValueLayout.JAVA_INT describes the layout of a Java int for segment access. arena.allocate(ValueLayout.JAVA_INT, 3) allocates space for three elements with that layout. setAtIndex and getAtIndex check the index against the segment; an out-of-bounds access fails rather than accidentally reading adjacent memory. The example's loop writes 1, 2, 3 and then adds the values, obtaining 6. An ordinary int[] could be used for this sum: the example uses native memory only to show the API's boundaries. When a program need not share data with native code or control an external layout, a Java array remains a simpler choice.
A segment can be sliced with asSlice to work on a part. Slicing does not make the underlying memory's lifetime independent: if the governing arena closes, the view is also invalid. A structure layout can compose values, sequences and padding; padding is space added to respect alignment constraints. An offset is the byte distance from the region's beginning. An offset or layout error may make one field read as another, even when the access remains within spatial bounds. Figure 28.2 shows a teaching layout with padding bytes. Before using it for a real C structure, verify its ABI, sizes and alignment on the program's compiler and platform.
The difference between logical size and physical arrangement is decisive. A structure with a four-byte field followed by an eight-byte one may have padding between fields to align the second. The figure uses four padding bytes as a teaching assumption, rather than a universal law for any compiler. MemoryLayout.structLayout lets us describe a sequence of members; paddingLayout makes the space required by the chosen layout explicit. For an array of structures we must also know each element's overall size, rather than only internal offsets. A description producing the right values on a single computer may be false on another ABI.
A VarHandle obtained from a path in the layout can make access to a nested field reusable. The name resembles the method handles of chapter 24, but the purpose here is reading or writing a position described by a memory layout. Reflection observes metadata of Java types and members; FFM describes data and calls beyond the JVM boundary. A handle's availability does not replace correct choices of lifetime, alignment and type.
From the C signature to the call
To call a native function, we must know which library contains it, which symbol identifies it and which binary signature it uses. SymbolLookup searches for the symbol and produces an address represented as a MemorySegment. Linker.nativeLinker() knows the current platform's ABI. FunctionDescriptor describes return and parameter types at native level. Finally, downcallHandle produces a MethodHandle that Java code can invoke. Figure 28.3 connects these steps; skipping one means relying on an unverified assumption.
In the complete program, we use strlen, a C-library function counting bytes before a C string's zero terminator. arena.allocateFrom("Java") creates an encoded, terminated string according to the API contract; because the example's ASCII letters occupy one byte each in UTF-8, the result is 4. If we wrote accented characters, strlen would count bytes, rather than Unicode characters or code points: precisely the limit to understand. The function is sought in the native linker's default lookup. This example was run on the working macOS and JDK 25 environment; other platforms may expose C symbols and types differently.
To construct a reproducible binding, knowing strlen by heart is insufficient. The official C signature returns size_t and receives a pointer to zero-terminated char. The FFM descriptor translates the pointer into ValueLayout.ADDRESS, while the string allocated in the arena supplies valid memory until the end of the try. The result is invoked with invokeExact, which requires exact Java types in the call; the cast to long makes the method handle's signature constructed in this environment explicit. If the function retained the pointer after returning, a confined arena closed at the end of the block would be too short-lived: we would have solved the immediate call but not the lifetime contract.
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
public class NativeMemory {
public static void main(String[] args) throws Throwable {
try (Arena arena = Arena.ofConfined()) {
MemorySegment numbers = arena.allocate(ValueLayout.JAVA_INT, 3);
for (int index = 0; index < 3; index++) {
numbers.setAtIndex(ValueLayout.JAVA_INT, index, index + 1);
}
int sum = 0;
for (int index = 0; index < 3; index++) {
sum += numbers.getAtIndex(ValueLayout.JAVA_INT, index);
}
System.out.println("Native sum: " + sum);
Linker linker = Linker.nativeLinker();
MemorySegment symbol = linker.defaultLookup().find("strlen")
.orElseThrow(() -> new IllegalStateException("strlen unavailable"));
MethodHandle strlen = linker.downcallHandle(symbol,
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
MemorySegment text = arena.allocateFrom("Java");
long length = (long) strlen.invokeExact(text);
System.out.println("Bytes before zero: " + length);
}
}
}
The compilation command is javac --release 25 NativeMemory.java. To execute a restricted method in a class-path program, use java --enable-native-access=ALL-UNNAMED NativeMemory. The option enables native access for all unnamed modules in that process; a modular application should specify the relevant module. Compilation with -Xlint:all reports the restricted method: the warning is relevant information, rather than a defect to hide. Enabling access does not automatically verify that the strlen descriptor is correct.
Warning – The signature depends on the ABI. In this test,
size_t, the C type returned bystrlen, is described asJAVA_LONG, consistently with the 64-bit ABI used in the verification environment. This is not a universal declaration: on 32-bit ABIs or with different representations, the binding must be adapted. An incorrect signature at the native boundary may corrupt memory or terminate the process. The chapter shows a reasoning method and a controlled case, rather than a binding library ready for every platform.
An upcall travels in the opposite direction: a native function calls Java code through a stub created by the linker. The stub must remain valid as long as the native library can use it; closing the arena too early invalidates the callback. An exception originating in called-back Java code must also be handled according to the boundary contract, rather than left to cross as if the C function knew Java exceptions. This is one reason to introduce upcalls only after understanding segments and downcalls.
Imagine a library registering a notification function and calling it after the registration call returns. If we create the stub inside a try (Arena arena = Arena.ofConfined()) ending immediately after registration, we hand the library an address destined to become invalid before the callback. The correction is not simply to use Arena.global(): we must establish who unregisters, wait until no callbacks are in progress and then close the appropriate arena. If notification comes from a different native thread, we must also verify access and concurrency constraints. The problem determines lifetime, rather than the reverse.
What the API checks and what remains ours
The API can check segment bounds, arena lifetime and, for a confined arena, the authorized thread. It cannot guarantee that a C library respects a received buffer's size, retains a pointer only for the allowed time or interprets the layout we intended. Spatial safety concerns addresses and bounds; temporal safety concerns when memory remains valid. Java-side checks reduce important errors, but native code can still violate the contract.
This also explains why verification cannot stop at positive output. Boundary tests are needed: undersized segments, a closed arena, a missing symbol, a signature unavailable on the platform and a native function returning an error code. The first three can be reproduced in a controlled Java test; an incorrect ABI signature must not be “tried to see if it works” in the main process, because failure may be a crash or corruption not immediately visible. In that case, start from headers, library documentation and a verified binding, then use isolated tests on the declared platform.
A tool such as jextract can generate bindings from C headers, avoiding many manual transcriptions. It is an integration-path tool, rather than a promise that every function automatically becomes portable or safe. The build must fix the versions of the tool, headers, compiler, architecture and libraries used. If the ABI changes, bindings and tests must be rechecked. The Vector API in chapter 23 solves another problem: processing data with SIMD operations. Vectors can be used on data arriving from segments, but this does not merge the two APIs' stability, risks and purposes.
Verification and transfer
The first check changes the number of allocated elements from three to two while leaving three writes: the program must fail the bounds check, rather than print an invented sum. The second retains a segment in a variable, closes the arena and tries to read it: it must fail because lifetime has ended. Do not insert the second test in the normal flow, where it would interrupt the rest of the example. These two experiments distinguish spatial and temporal errors.
The transfer changes the C function. A library requires a pointer to a structure with two integers, retains the pointer until a callback and then returns a status code. Before writing downcallHandle, readers must answer: which layout matches the structure on this ABI? Which arena covers the pointer's entire lifetime? Which thread can access it? How is the status code interpreted? Which test checks closure? If an answer is missing, a program that “compiles” has not yet solved the problem.
Essential references. The Java 25
java.lang.foreignpackage describes segments, layouts and external functions; theArenaspecification defines lifetime and access; theLinkerspecification clarifies the role of the ABI and restricted methods. Thestrlencase remains bound to the declared native environment.