Foreign Function & Memory API
suggest changeThe Foreign Function & Memory API (FFM, package java.lang.foreign) lets Java code call C functions and work with memory outside the Java heap, all in plain Java. You don't write any C glue code, you don't need javah/javac -h and you don't compile a separate JNI library.
It became a standard feature in Java 22 (JEP 454), after previews in Java 19-21 and incubators in Java 14-18. Everything below runs on JDK 22 or newer without --enable-preview. The examples were run on JDK 25 on Windows x64.
The API has a few main parts:
Arenacontrols the lifetime of native memory: memory is freed when the arena is closed.MemorySegmentis a bounds-checked view of a block of memory (native, on-heap or memory-mapped).MemoryLayoutandValueLayoutdescribe C types:int,double, pointers, structs, arrays.Linkerturns a native function address and aFunctionDescriptorinto aMethodHandle(a downcall), or turns a Java method into a C function pointer (an upcall).SymbolLookupfinds functions in the C runtime, in system libraries or in your own shared library.
Calling strlen
Here's a complete program that calls strlen from the C runtime:
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
public class Strlen {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
MemorySegment strlenAddr = linker.defaultLookup().findOrThrow("strlen");
// size_t strlen(const char *s);
MethodHandle strlen = linker.downcallHandle(
strlenAddr,
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
try (Arena arena = Arena.ofConfined()) {
MemorySegment cString = arena.allocateFrom("Hello, native world!");
long len = (long) strlen.invokeExact(cString);
System.out.println("strlen = " + len);
System.out.println("segment size = " + cString.byteSize());
}
}
}
$ java --enable-native-access=ALL-UNNAMED Strlen.java
strlen = 20
segment size = 21
Step by step:
Linker.nativeLinker()returns the linker for the current platform's calling convention (Windows x64, System V x64, AArch64 and so on).defaultLookup()finds commonly used libraries for the platform: the C runtime on Windows, libc on Linux and macOS.findOrThrowreturns the function's address as aMemorySegment.FunctionDescriptor.of(returnLayout, argLayouts...)describes the C signature.size_tis 64-bit on 64-bit platforms, so it maps toJAVA_LONG. Any pointer maps toADDRESS. UseFunctionDescriptor.ofVoid(...)for functions returningvoid.arena.allocateFrom(String)copies the string into native memory as UTF-8 and adds the terminating NUL, which is why the segment is 21 bytes.invokeExactcalls the function. The cast to(long)is not optional: withinvokeExactthe argument and return types at the call site must match the handle type exactly. Writingint len = (int) strlen.invokeExact(cString);compiles, but fails at run time:
Exception in thread "main" java.lang.invoke.WrongMethodTypeException: handle's method type (MemorySegment)long but found (MemorySegment)int
Store method handles in static final fields in real code. The JIT can then inline the call, and creating a downcall handle is relatively expensive, so you want to do it once.
Native access warnings and --enable-native-access
Linker::downcallHandle, SymbolLookup.libraryLookup, MemorySegment::reinterpret and a few other methods are restricted: used wrongly they can crash the JVM or corrupt memory. Running the same program without the flag prints a warning:
WARNING: A restricted method in java.lang.foreign.Linker has been called
WARNING: java.lang.foreign.Linker::downcallHandle has been called by Strlen in an unnamed module (file:/C:/.../ffm/Strlen.java)
WARNING: Use --enable-native-access=ALL-UNNAMED to avoid a warning for callers in this module
WARNING: Restricted methods will be blocked in a future release unless native access is enabled
strlen = 20
segment size = 21
You can grant native access in three ways:
--enable-native-access=ALL-UNNAMEDfor code on the class path, or--enable-native-access=com.example.mymodulefor named modules.Enable-Native-Access: ALL-UNNAMEDin the manifest of an executable JAR (the only value allowed there), sojava -jar app.jarruns without warnings.jlink's--add-optionswhen you build a custom runtime image.
Since Java 24 (JEP 472) the same rules apply to loading JNI libraries. --illegal-native-access=deny turns the warning into an error today, which is the planned default for a future release:
$ java --illegal-native-access=deny Strlen.java
Exception in thread "main" java.lang.IllegalCallerException: Illegal native access from an unnamed module (file:/C:/.../ffm/Strlen.java)
at java.base/java.lang.Module.ensureNativeAccess(Module.java:307)
Memory segments
A MemorySegment has an address, a size and a lifetime. Every access is checked against all three, so you get an exception instead of a crash:
import java.lang.foreign.*;
import static java.lang.foreign.ValueLayout.*;
public class Segments {
public static void main(String[] args) {
MemorySegment leaked;
try (Arena arena = Arena.ofConfined()) {
// 10 C ints, zero-initialized, off-heap
MemorySegment ints = arena.allocate(JAVA_INT, 10);
for (int i = 0; i < 10; i++) {
ints.setAtIndex(JAVA_INT, i, i * i);
}
System.out.println("size in bytes: " + ints.byteSize());
System.out.println("ints[7] = " + ints.getAtIndex(JAVA_INT, 7));
int[] copy = ints.toArray(JAVA_INT);
System.out.println(java.util.Arrays.toString(copy));
MemorySegment tail = ints.asSlice(8 * 4); // last two ints
System.out.println("tail[0] = " + tail.getAtIndex(JAVA_INT, 0));
try {
ints.getAtIndex(JAVA_INT, 10);
} catch (IndexOutOfBoundsException e) {
System.out.println("out of bounds: " + e.getMessage());
}
leaked = ints;
}
try {
leaked.getAtIndex(JAVA_INT, 0);
} catch (IllegalStateException e) {
System.out.println("after close: " + e.getMessage());
}
}
}
size in bytes: 40
ints[7] = 49
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
tail[0] = 64
out of bounds: Out of bound access on segment MemorySegment{ kind: native, address: 0x1ffa6d324d0, byteSize: 40 }; new offset = 40; new length = 4
after close: Already closed
get/set take a byte offset, and getAtIndex/setAtIndex take an element index that gets multiplied by the layout size. asSlice creates a view of part of a segment without copying. Native memory from arena.allocate is zero-filled.
Reading a segment after its arena was closed throws IllegalStateException. That's the main safety win over sun.misc.Unsafe and ByteBuffer.allocateDirect: no use-after-free, no reading past the end, and memory is freed when you say so, not whenever the GC gets around to it.
Arenas
The kind of arena decides who can access the memory and when it's freed:
| Arena | Freed | Threads | Typical use |
|---|---|---|---|
Arena.ofConfined() |
on close() |
only the creating thread | most native calls |
Arena.ofShared() |
on close() |
any thread | memory shared by worker threads |
Arena.ofAuto() |
by the GC, when unreachable | any thread | when there's no clear owner |
Arena.global() |
never | any thread | constants, things that live as long as the program |
import java.lang.foreign.*;
import static java.lang.foreign.ValueLayout.*;
public class Arenas {
public static void main(String[] args) throws Exception {
try (Arena confined = Arena.ofConfined()) {
MemorySegment seg = confined.allocate(JAVA_LONG);
Thread t = Thread.ofPlatform().start(() -> {
try {
seg.set(JAVA_LONG, 0, 42);
} catch (WrongThreadException e) {
System.out.println("other thread: " + e.getMessage());
}
});
t.join();
}
try (Arena shared = Arena.ofShared()) {
MemorySegment slots = shared.allocate(JAVA_LONG, 4);
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; i++) {
int n = i; // each thread writes its own slot
threads[i] = Thread.ofPlatform().start(() ->
slots.setAtIndex(JAVA_LONG, n, n * 10L));
}
for (Thread t : threads) t.join();
System.out.println("shared: " + java.util.Arrays.toString(slots.toArray(JAVA_LONG)));
}
MemorySegment auto = Arena.ofAuto().allocate(1024); // freed by the GC
MemorySegment forever = Arena.global().allocate(1024); // never freed
System.out.println(auto.scope().isAlive() + " " + forever.scope().isAlive());
try {
Arena.global().close();
} catch (UnsupportedOperationException e) {
System.out.println("global arena can't be closed");
}
}
}
other thread: Attempted access outside owning thread
shared: [0, 10, 20, 30]
true true
global arena can't be closed
Use try-with-resources with confined arenas whenever you can. They're the cheapest to close. Closing a shared arena has to make sure no other thread is accessing its memory at that moment, so it costs more.
Calling Win32 functions and filling a struct
SymbolLookup.libraryLookup(name, arena) loads a library with the operating system's loader (LoadLibrary on Windows, dlopen elsewhere) and unloads it when the arena is closed. Here we call three functions from kernel32.dll. GetLocalTime fills a SYSTEMTIME struct, which we describe with a StructLayout and read through VarHandles:
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import static java.lang.foreign.ValueLayout.*;
public class Kernel32 {
// typedef struct _SYSTEMTIME { WORD wYear; WORD wMonth; ... WORD wMilliseconds; }
static final StructLayout SYSTEMTIME = MemoryLayout.structLayout(
JAVA_SHORT.withName("wYear"),
JAVA_SHORT.withName("wMonth"),
JAVA_SHORT.withName("wDayOfWeek"),
JAVA_SHORT.withName("wDay"),
JAVA_SHORT.withName("wHour"),
JAVA_SHORT.withName("wMinute"),
JAVA_SHORT.withName("wSecond"),
JAVA_SHORT.withName("wMilliseconds"));
static final VarHandle YEAR = SYSTEMTIME.varHandle(MemoryLayout.PathElement.groupElement("wYear"));
static final VarHandle MONTH = SYSTEMTIME.varHandle(MemoryLayout.PathElement.groupElement("wMonth"));
static final VarHandle DAY = SYSTEMTIME.varHandle(MemoryLayout.PathElement.groupElement("wDay"));
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
try (Arena arena = Arena.ofConfined()) {
SymbolLookup kernel32 = SymbolLookup.libraryLookup("kernel32", arena);
// DWORD GetCurrentProcessId(void);
MethodHandle getPid = linker.downcallHandle(
kernel32.findOrThrow("GetCurrentProcessId"),
FunctionDescriptor.of(JAVA_INT));
// ULONGLONG GetTickCount64(void);
MethodHandle getTicks = linker.downcallHandle(
kernel32.findOrThrow("GetTickCount64"),
FunctionDescriptor.of(JAVA_LONG));
// void GetLocalTime(LPSYSTEMTIME lpSystemTime);
MethodHandle getLocalTime = linker.downcallHandle(
kernel32.findOrThrow("GetLocalTime"),
FunctionDescriptor.ofVoid(ADDRESS));
int pid = (int) getPid.invokeExact();
System.out.println("pid from kernel32: " + pid);
System.out.println("pid from Java: " + ProcessHandle.current().pid());
long ticks = (long) getTicks.invokeExact();
System.out.printf("uptime: %.1f hours%n", ticks / 3_600_000.0);
System.out.println("SYSTEMTIME size: " + SYSTEMTIME.byteSize());
MemorySegment st = arena.allocate(SYSTEMTIME);
getLocalTime.invokeExact(st);
short year = (short) YEAR.get(st, 0L);
short month = (short) MONTH.get(st, 0L);
short day = (short) DAY.get(st, 0L);
System.out.printf("today: %04d-%02d-%02d%n", year, month, day);
}
}
}
pid from kernel32: 36660
pid from Java: 36660
uptime: 91.3 hours
SYSTEMTIME size: 16
today: 2026-10-18
Things to note:
- Java has no unsigned types.
DWORDmaps toJAVA_INT,WORDtoJAVA_SHORTandULONGLONGtoJAVA_LONG. UseInteger.toUnsignedLongorShort.toUnsignedIntwhen the high bit can be set. - Struct
VarHandles take the segment and a base offset (0Lhere). The0Lmust be alongand the result must be cast to the exact type (short), for the same reason as withinvokeExact. - C
longis 32 bits on Windows and 64 bits on Linux/macOS. Don't hardcodeJAVA_LONGfor Clongin portable code:linker.canonicalLayouts().get("long")gives the right layout for the platform.
Reading errno and GetLastError
The JVM itself calls native code, so by the time your Java code calls GetLastError the value may already be overwritten. Use Linker.Option.captureCallState to save it right after the call:
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import java.nio.charset.StandardCharsets;
import static java.lang.foreign.ValueLayout.*;
public class LastError {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
Linker.Option ccs = Linker.Option.captureCallState("GetLastError");
StructLayout stateLayout = Linker.Option.captureStateLayout();
VarHandle lastError = stateLayout.varHandle(
MemoryLayout.PathElement.groupElement("GetLastError"));
try (Arena arena = Arena.ofConfined()) {
SymbolLookup kernel32 = SymbolLookup.libraryLookup("kernel32", arena);
// BOOL DeleteFileW(LPCWSTR lpFileName);
MethodHandle deleteFile = linker.downcallHandle(
kernel32.findOrThrow("DeleteFileW"),
FunctionDescriptor.of(JAVA_INT, ADDRESS),
ccs); // the handle gets an extra leading MemorySegment parameter
MemorySegment state = arena.allocate(stateLayout);
MemorySegment name = arena.allocateFrom("no-such-file.txt", StandardCharsets.UTF_16LE);
int ok = (int) deleteFile.invokeExact(state, name);
int err = (int) lastError.get(state, 0L);
System.out.println("DeleteFileW returned " + ok + ", GetLastError = " + err);
System.out.println("state layout: " + stateLayout);
}
}
}
DeleteFileW returned 0, GetLastError = 2
state layout: [i4(GetLastError)i4(WSAGetLastError)i4(errno)]
Error 2 is ERROR_FILE_NOT_FOUND. On Linux and macOS the only captured value is "errno". The example also shows that the W (wide) Win32 functions need UTF-16LE strings, which allocateFrom(String, Charset) takes care of.
Upcalls: qsort with a Java comparator
C's qsort takes a function pointer for comparing elements. Linker.upcallStub creates a C function pointer that calls a Java method:
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.Arrays;
import static java.lang.foreign.ValueLayout.*;
public class Qsort {
// int compar(const void *a, const void *b) -- implemented in Java
static int compareInts(MemorySegment a, MemorySegment b) {
return Integer.compare(a.get(JAVA_INT, 0), b.get(JAVA_INT, 0));
}
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
// void qsort(void *base, size_t nmemb, size_t size,
// int (*compar)(const void *, const void *));
MethodHandle qsort = linker.downcallHandle(
linker.defaultLookup().findOrThrow("qsort"),
FunctionDescriptor.ofVoid(ADDRESS, JAVA_LONG, JAVA_LONG, ADDRESS));
// the pointers passed to the comparator point to one int each
AddressLayout intPtr = ADDRESS.withTargetLayout(JAVA_INT);
FunctionDescriptor comparDesc = FunctionDescriptor.of(JAVA_INT, intPtr, intPtr);
MethodHandle compareHandle = MethodHandles.lookup().findStatic(
Qsort.class, "compareInts",
MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class));
try (Arena arena = Arena.ofConfined()) {
// a C function pointer that calls back into Java
MemorySegment comparFunc = linker.upcallStub(compareHandle, comparDesc, arena);
int[] data = {42, 7, 19, -3, 100, 0, 7};
MemorySegment array = arena.allocateFrom(JAVA_INT, data);
qsort.invokeExact(array, (long) data.length, JAVA_INT.byteSize(), comparFunc);
System.out.println(Arrays.toString(array.toArray(JAVA_INT)));
}
}
}
[-3, 0, 7, 7, 19, 42, 100]
Pointers that come from native code are zero-length segments: Java knows the address but not how much memory is behind it. ADDRESS.withTargetLayout(JAVA_INT) tells the linker that each pointer points to one int, so the comparator gets 4-byte segments it can read from. Without the target layout a.get(JAVA_INT, 0) would throw IndexOutOfBoundsException.
The upcall stub is freed when its arena is closed. Native code must not call it after that. Also, an exception thrown out of an upcall can't propagate through C frames, so the JVM terminates instead. Catch exceptions inside the upcall method.
Calling your own library: structs, padding and pointers
Here's a small C library, compiled into geom.dll with MSVC (cl -LD geom.c; on Linux use gcc -shared -fPIC -o libgeom.so geom.c):
// geom.h
#ifdef _WIN32
#define API __declspec(dllexport)
#else
#define API
#endif
typedef struct {
double x;
double y;
} Point;
typedef struct {
int id; /* 4 bytes, then 4 bytes of padding */
double score;
char tag[4];
} Player;
API Point midpoint(Point a, Point b);
API double average_score(const Player *players, int count);
API const char *geom_version(void);
// geom.c
#include "geom.h"
Point midpoint(Point a, Point b) {
Point m = { (a.x + b.x) / 2, (a.y + b.y) / 2 };
return m;
}
double average_score(const Player *players, int count) {
double sum = 0;
for (int i = 0; i < count; i++) sum += players[i].score;
return count > 0 ? sum / count : 0;
}
const char *geom_version(void) {
return "geom 1.0";
}
The Java side has to describe Player exactly as the C compiler lays it out, including padding. FFM doesn't insert padding for you. If you leave it out, structLayout refuses the misaligned double:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid alignment constraint for member layout: d8(score)
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import java.nio.file.Path;
import static java.lang.foreign.MemoryLayout.PathElement.groupElement;
import static java.lang.foreign.ValueLayout.*;
public class Geom {
static final StructLayout POINT = MemoryLayout.structLayout(
JAVA_DOUBLE.withName("x"),
JAVA_DOUBLE.withName("y"));
static final StructLayout PLAYER = MemoryLayout.structLayout(
JAVA_INT.withName("id"),
MemoryLayout.paddingLayout(4), // C inserts this to align score
JAVA_DOUBLE.withName("score"),
MemoryLayout.sequenceLayout(4, JAVA_BYTE).withName("tag"),
MemoryLayout.paddingLayout(4)); // round the size up to 8
static final VarHandle PX = POINT.varHandle(groupElement("x"));
static final VarHandle PY = POINT.varHandle(groupElement("y"));
static final VarHandle PLAYER_ID = PLAYER.varHandle(groupElement("id"));
static final VarHandle PLAYER_SCORE = PLAYER.varHandle(groupElement("score"));
static final long TAG_OFFSET = PLAYER.byteOffset(groupElement("tag"));
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
try (Arena arena = Arena.ofConfined()) {
SymbolLookup geom = SymbolLookup.libraryLookup(Path.of("geom.dll").toAbsolutePath(), arena);
MethodHandle midpoint = linker.downcallHandle(
geom.findOrThrow("midpoint"),
FunctionDescriptor.of(POINT, POINT, POINT)); // structs by value
MethodHandle averageScore = linker.downcallHandle(
geom.findOrThrow("average_score"),
FunctionDescriptor.of(JAVA_DOUBLE, ADDRESS, JAVA_INT));
MethodHandle version = linker.downcallHandle(
geom.findOrThrow("geom_version"),
FunctionDescriptor.of(ADDRESS));
MemorySegment a = arena.allocate(POINT);
PX.set(a, 0L, 1.0);
PY.set(a, 0L, 2.0);
MemorySegment b = arena.allocate(POINT);
PX.set(b, 0L, 5.0);
PY.set(b, 0L, 8.0);
// a struct returned by value needs memory: pass an allocator first
MemorySegment m = (MemorySegment) midpoint.invokeExact((SegmentAllocator) arena, a, b);
System.out.printf("midpoint = (%.1f, %.1f)%n", (double) PX.get(m, 0L), (double) PY.get(m, 0L));
System.out.println("sizeof(Player) = " + PLAYER.byteSize());
int[] ids = {1, 2, 3};
double[] scores = {80.5, 92.0, 67.25};
String[] tags = {"ann", "bob", "cyd"};
MemorySegment players = arena.allocate(PLAYER, ids.length);
for (int i = 0; i < ids.length; i++) {
MemorySegment p = players.asSlice(i * PLAYER.byteSize(), PLAYER);
PLAYER_ID.set(p, 0L, ids[i]);
PLAYER_SCORE.set(p, 0L, scores[i]);
p.setString(TAG_OFFSET, tags[i]); // writes "ann\0" into char tag[4]
}
double avg = (double) averageScore.invokeExact(players, ids.length);
System.out.println("average score = " + avg);
MemorySegment v = (MemorySegment) version.invokeExact();
System.out.println("returned segment size = " + v.byteSize());
// trust the C side: the string is NUL-terminated somewhere
System.out.println("version = " + v.reinterpret(Long.MAX_VALUE).getString(0));
}
}
}
midpoint = (3.0, 5.0)
sizeof(Player) = 24
average score = 79.91666666666667
returned segment size = 0
version = geom 1.0
SymbolLookup.libraryLookup(Path, Arena)loads a library from an exact path.libraryLookup(String, Arena)passes the name to the OS loader, which searches its usual places (PATHon Windows,LD_LIBRARY_PATHon Linux).SymbolLookup.loaderLookup()finds symbols in libraries loaded withSystem.loadLibrary/System.load, as in Loading native libraries.- Structs passed by value use the struct layout directly in the descriptor. When a function returns a struct by value, the method handle gets an extra leading
SegmentAllocatorparameter that allocates memory for the result. AnArenais aSegmentAllocator. - A
const char *return value comes back as a zero-length segment.reinterpret(size)gives it a size you choose. It's a restricted method because Java can't check whether that memory really exists.
Generating bindings with jextract
Writing layouts and descriptors by hand gets tedious for real C APIs. jextract reads C headers (it uses libclang) and generates the Java bindings. It isn't part of the JDK: download a build matching your JDK from jdk.java.net/jextract and unpack it.
$ jextract --version
jextract 25
JDK version 25+37-3491
LibClang version clang version 13.0.0
$ jextract --output src --target-package org.example.geom --library geom geom.h
$ find src -name '*.java'
src/org/example/geom/geom_h$shared.java
src/org/example/geom/geom_h.java
src/org/example/geom/Player.java
src/org/example/geom/Point.java
geom_h has a static method for every function and C_INT, C_DOUBLE, C_POINTER and similar layout constants. Each struct gets its own class with a layout, getters, setters and allocation helpers. jextract figured out the padding on its own:
private static final GroupLayout $LAYOUT = MemoryLayout.structLayout(
geom_h.C_INT.withName("id"),
MemoryLayout.paddingLayout(4),
geom_h.C_DOUBLE.withName("score"),
MemoryLayout.sequenceLayout(4, geom_h.C_CHAR).withName("tag"),
MemoryLayout.paddingLayout(4)
).withName("$anon$12:9");
The previous program shrinks to this:
import java.lang.foreign.*;
import org.example.geom.Player;
import org.example.geom.Point;
import static org.example.geom.geom_h.*;
public class UseGeom {
public static void main(String[] args) {
try (Arena arena = Arena.ofConfined()) {
MemorySegment a = Point.allocate(arena);
Point.x(a, 1.0);
Point.y(a, 2.0);
MemorySegment b = Point.allocate(arena);
Point.x(b, 5.0);
Point.y(b, 8.0);
MemorySegment m = midpoint(arena, a, b);
System.out.printf("midpoint = (%.1f, %.1f)%n", Point.x(m), Point.y(m));
MemorySegment players = Player.allocateArray(2, arena);
Player.score(Player.asSlice(players, 0), 70.0);
Player.score(Player.asSlice(players, 1), 90.0);
System.out.println("average = " + average_score(players, 2));
System.out.println("version = " + geom_version().getString(0));
}
}
}
$ javac -d classes $(find src -name '*.java') UseGeom.java
$ java --enable-native-access=ALL-UNNAMED -cp classes UseGeom
midpoint = (3.0, 5.0)
average = 80.0
version = geom 1.0
The generated methods throw no checked exceptions, so there's no throws Throwable. The generated C_POINTER layout has a large target layout, so geom_version().getString(0) works without reinterpret. --library geom makes the bindings load the library through System.mapLibraryName("geom") (geom.dll, libgeom.so, libgeom.dylib), so the OS loader has to be able to find it. Use --library :/full/path/to/libgeom.so to bake in a path, or --use-system-load-library to load it with System.loadLibrary from java.library.path. Generated bindings are tied to the platform they were generated on: run jextract on each platform where type sizes differ (for example long on Windows vs. Linux).
Off-heap memory without Unsafe
FFM is also the supported replacement for the memory-access methods of sun.misc.Unsafe. Those methods were deprecated for removal in Java 23 (JEP 471), and since Java 24 they print a warning on first use (JEP 498). Besides arena.allocate, segments can map files and wrap Java arrays:
import java.lang.foreign.*;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.file.*;
import static java.lang.foreign.ValueLayout.*;
import static java.nio.file.StandardOpenOption.*;
public class Mapped {
public static void main(String[] args) throws Exception {
Path file = Path.of("numbers.bin");
long count = 1_000_000;
try (FileChannel ch = FileChannel.open(file, CREATE, READ, WRITE, TRUNCATE_EXISTING);
Arena arena = Arena.ofConfined()) {
MemorySegment map = ch.map(FileChannel.MapMode.READ_WRITE, 0, count * 4, arena);
for (long i = 0; i < count; i++) {
map.setAtIndex(JAVA_INT, i, (int) i);
}
long sum = 0;
for (long i = 0; i < count; i++) {
sum += map.getAtIndex(JAVA_INT, i);
}
System.out.println("sum = " + sum + ", file size = " + Files.size(file));
} // the mapping is released here, not when the GC gets around to it
Files.delete(file);
// heap segments wrap Java arrays and use the same API;
// byte[] memory is only 1-byte aligned, hence the _UNALIGNED layout
MemorySegment heap = MemorySegment.ofArray(new byte[8]);
heap.set(JAVA_INT_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN), 0, 0xCAFEBABE);
System.out.printf("first byte: %02X, isNative: %b%n", heap.get(JAVA_BYTE, 0), heap.isNative());
}
}
sum = 499999500000, file size = 4000000
first byte: CA, isNative: false
Unlike MappedByteBuffer, a mapped segment can be bigger than 2 GB (offsets are long), and the mapping is released deterministically, so on Windows Files.delete works right after the arena is closed. With the aligned JAVA_INT layout the last set would fail with IllegalArgumentException: Target offset 0 is incompatible with alignment constraint 4, because a byte[] isn't guaranteed to be 4-byte aligned. None of these memory operations are restricted, so they don't need --enable-native-access.
FFM vs. JNI vs. JNA
| JNI | JNA | FFM | |
|---|---|---|---|
| Part of the JDK | yes | no (library) | yes, since Java 22 |
| Native glue code | C code per function, compiled per platform | none | none |
| Calling existing C libraries | needs a wrapper library | direct | direct |
| Speed | fast | much slower (reflection, libffi) | as fast as JNI or faster |
| Off-heap memory safety | manual | manual (Memory, Pointer) |
bounds, lifetime and thread checks |
| Callbacks from C | JNIEnv calls from C |
interfaces | upcall stubs |
| Binding generation | javac -h (Java to C) |
by hand | jextract (C to Java) |
| Minimum Java version | any | any | 22 (preview in 19-21) |
New code that targets Java 22 or later should use FFM. JNI is still the choice for code that has to run on older JVMs, or for C code that needs to call back into the JVM a lot (creating Java objects, calling arbitrary Java methods through JNIEnv). JNA is still handy on older Java versions. Lucene, for example, uses memory segments for its memory-mapped index files. If you're migrating from JNI, see Calling C methods from Java and Calling Java methods from C callback for the JNI equivalents of the examples above.
Summary
java.lang.foreignhas been standard since Java 22: call C functions and manage off-heap memory without JNI glue code.- Allocate native memory from an
Arena. It's freed when the arena closes, and segments check bounds, lifetime and owning thread on every access. - Describe C types with
ValueLayoutconstants andMemoryLayout.structLayout, including explicitpaddingLayout. Read and write fields withVarHandles fromlayout.varHandle(groupElement(...)). Linker.downcallHandle+FunctionDescriptorgives aMethodHandlefor a C function. UseinvokeExactwith exact casts and store handles instatic finalfields.Linker.upcallStubturns a Java method into a C function pointer, for example aqsortcomparator.- Find functions with
linker.defaultLookup()(C runtime),SymbolLookup.libraryLookup(any library by name or path) orSymbolLookup.loaderLookup(). - Restricted methods warn unless you pass
--enable-native-access=ALL-UNNAMED(or setEnable-Native-Accessin the JAR manifest). A future release will turn the warning into an error. - For non-trivial C APIs, generate bindings with
jextractinstead of writing layouts by hand.