Sub topic 11
Callbacks: letting C call Java
Many C libraries take a function pointer: a sort routine that wants a comparator, an event library that wants a handler, a parser that wants a visitor. To use them from Java, you need a C-callable function pointer that runs a Java method. The FFM API calls this an upcall stub. This chapter shows how to build one, what the JVM does when C calls it, and the failure modes that matter.
It assumes you can already create a downcall handle with Linker, FunctionDescriptor and MethodHandle, and that you know how arenas and layouts work from the earlier chapters. The examples are written for Java 22. In Java 23 and later, allocateArray is named allocateFrom.
What an upcall stub is
A downcall goes from Java into C. An upcall goes the other way. C code cannot call a MethodHandle directly, because it only understands machine-level function pointers. Linker.upcallStub bridges this gap. It generates a small piece of native code that:
- Receives a call using the platform's C calling convention.
- Converts the arguments into Java values.
- Invokes your
MethodHandle. - Converts the return value back to the C representation.
The stub is returned as a MemorySegment holding the address of that native code. You pass it to C anywhere a function pointer is expected.
MemorySegment upcallStub(MethodHandle target,
FunctionDescriptor function,
Arena arena,
Linker.Option... options)The three required arguments are the following.
| Parameter | Role |
|---|---|
| `target` | The Java code to run. A `MethodHandle` whose type must match the descriptor. |
| `function` | The C signature of the function pointer, as seen by the C caller. |
| `arena` | Controls how long the stub stays valid. |
The returned segment has length zero. You can pass it to native code, but you cannot read from it.
The round trip
The sequence below shows what happens when you sort an array with qsort and a Java comparator. The Java thread stays on the call stack the whole time. C calls back into Java on that same thread.
Step 1: describe the callback signature
The C type is int (*cmp)(const void *, const void *). The matching descriptor is (pointer, pointer) -> int. There is one detail here that catches many people.
Pointers that arrive in an upcall are MemorySegments of length zero, because the JVM cannot know how much memory they point to. If you read through one, you get an IndexOutOfBoundsException. To avoid this, declare the pointee type with withTargetLayout:
AddressLayout intPtr = ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT);
FunctionDescriptor cmpDesc =
FunctionDescriptor.of(ValueLayout.JAVA_INT, intPtr, intPtr);The segments passed to your method then have length 4 and are readable as int. The alternative is calling reinterpret(long) on the segment. That is a restricted method, so it needs native access and removes the bounds protection. Prefer the target layout whenever you know the pointee type.
Step 2: write the Java target
The target is any MethodHandle. Its MethodType must match what the descriptor implies: int for JAVA_INT, MemorySegment for an address, long for JAVA_LONG, and so on. A mismatch throws IllegalArgumentException when you create the stub.
static int compare(MemorySegment a, MemorySegment b) {
return Integer.compare(a.get(ValueLayout.JAVA_INT, 0),
b.get(ValueLayout.JAVA_INT, 0));
}You obtain the handle with MethodHandles.lookup().findStatic(...).
Step 3: create the stub and call C
This is the complete program. It is the same pattern as the sorting example in the tutorial's code samples.
import java.lang.foreign.AddressLayout;
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;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.Arrays;
public class QsortDemo {
static int compare(MemorySegment a, MemorySegment b) {
return Integer.compare(a.get(ValueLayout.JAVA_INT, 0), b.get(ValueLayout.JAVA_INT, 0));
}
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
AddressLayout intPtr = ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT);
// void qsort(void *base, size_t n, size_t size, int (*cmp)(const void *, const void *));
// size_t is modeled as JAVA_LONG, which is correct on 64-bit platforms.
MethodHandle qsort = linker.downcallHandle(
linker.defaultLookup().find("qsort").orElseThrow(),
FunctionDescriptor.ofVoid(ValueLayout.ADDRESS, ValueLayout.JAVA_LONG,
ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
MethodHandle cmp = MethodHandles.lookup().findStatic(QsortDemo.class, "compare",
MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class));
FunctionDescriptor cmpDesc = FunctionDescriptor.of(ValueLayout.JAVA_INT, intPtr, intPtr);
try (Arena arena = Arena.ofConfined()) {
MemorySegment stub = linker.upcallStub(cmp, cmpDesc, arena);
MemorySegment array = arena.allocateArray(ValueLayout.JAVA_INT, 5, 3, 9, 1, 7);
qsort.invokeExact(array, 5L, 4L, stub);
System.out.println(Arrays.toString(array.toArray(ValueLayout.JAVA_INT))); // [1, 3, 5, 7, 9]
}
}
}Run it with --enable-native-access=ALL-UNNAMED. Both downcallHandle and upcallStub are restricted methods.
Carrying state into a callback
C callbacks often have no user-data parameter, or you may not want to use one. In Java you can bind state into the handle instead. MethodHandle.bindTo fixes the receiver of an instance method, and MethodHandles.insertArguments fixes leading arguments. The stub's type is then the remaining parameters, which must match the descriptor.
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;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.Arrays;
public class CountingSort {
private int calls;
int compareDescending(MemorySegment a, MemorySegment b) {
calls++;
return Integer.compare(b.get(ValueLayout.JAVA_INT, 0), a.get(ValueLayout.JAVA_INT, 0));
}
void run() throws Throwable {
Linker linker = Linker.nativeLinker();
var intPtr = ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT);
MethodHandle qsort = linker.downcallHandle(
linker.defaultLookup().find("qsort").orElseThrow(),
FunctionDescriptor.ofVoid(ValueLayout.ADDRESS, ValueLayout.JAVA_LONG,
ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
MethodHandle cmp = MethodHandles.lookup()
.findVirtual(CountingSort.class, "compareDescending",
MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class))
.bindTo(this);
try (Arena arena = Arena.ofConfined()) {
MemorySegment stub = linker.upcallStub(cmp,
FunctionDescriptor.of(ValueLayout.JAVA_INT, intPtr, intPtr), arena);
MemorySegment array = arena.allocateArray(ValueLayout.JAVA_INT, 4, 8, 2, 6);
qsort.invokeExact(array, 4L, 4L, stub);
System.out.println(Arrays.toString(array.toArray(ValueLayout.JAVA_INT)));
System.out.println("comparisons: " + calls);
}
}
public static void main(String[] args) throws Throwable {
new CountingSort().run();
}
}The array prints as [8, 6, 4, 2]. The comparison count depends on the C library's sorting algorithm, so do not rely on a specific number.
Lifetime of the stub
The arena you pass to upcallStub owns the native code of the stub. When the arena closes, the stub is freed. If C still holds the pointer and calls it afterwards, the process jumps into freed memory. Java cannot catch that. Choose the arena by asking how long C might call back.
| Situation | Arena |
|---|---|
| C calls back only during the downcall, like `qsort` | `Arena.ofConfined()` around the call |
| C stores the pointer and calls back later, from any thread | `Arena.global()`, or a shared arena you close only after unregistering |
| The registration has no clear end | `Arena.ofAuto()`, so the garbage collector frees the stub once it is unreachable |
With ofAuto, keep a reference to the stub segment for as long as C may call it. If the stub segment becomes unreachable while C still holds the raw address, the collector can free it. With a shared arena, first tell the library to forget the callback, then close the arena.
Threads and exceptions
Which thread runs the callback. For qsort, the callback runs on the thread that made the downcall. A library that creates its own threads may call your stub from a thread the JVM has never seen. The upcall attaches that thread to the JVM for the duration of the call. Your Java code must then be safe for concurrent use. A confined arena cannot be accessed from such a thread.
Exceptions. An exception cannot propagate through C frames. If your target throws, the JVM terminates the process immediately. This is a hard crash, not a Java stack trace you can handle. This includes accidental errors like the IndexOutOfBoundsException described earlier. Wrap the body of each callback:
static int safeCompare(MemorySegment a, MemorySegment b) {
try {
return Integer.compare(a.get(ValueLayout.JAVA_INT, 0), b.get(ValueLayout.JAVA_INT, 0));
} catch (Throwable t) {
failure = t; // record it, then return a harmless value
return 0;
}
}Here failure is a static field. After the downcall returns, check it and rethrow in ordinary Java code.
Common mistakes
- Zero-length pointer arguments. Forgetting
withTargetLayoutmakes every read in the callback fail. - Type mismatch. The
MethodTypeof the target must equal the descriptor's Java types. UsingIntegerinstead ofint, orlongwhere the C type isint, fails at stub creation. - Wrong size for
size_t. On a 32-bit platformsize_tis 4 bytes. TheJAVA_LONGmodel is only correct on 64-bit. - Blocking or slow callbacks. The calling C code, and often a lock it holds, waits for your Java method. Keep callbacks short.
- Closing the arena too early. This is the most dangerous mistake because it fails only when C next calls the pointer.
Exercise
A C library function register_handler(void (*h)(int)) stores your function pointer and invokes it later from its own worker thread. Which arena would you give upcallStub, why can't you use Arena.ofConfined(), and what must your handler do about exceptions?
Show answer
Use an arena whose lifetime covers every later callback, such as Arena.global(), or a shared arena that you close only after unregistering the handler from the library. Arena.ofAuto() also works if you keep the stub segment reachable. A confined arena is closed at the end of its try block, so the stub would be freed while the library still holds the pointer. It also can't be accessed from another thread. The handler must catch Throwable itself, because an exception escaping an upcall terminates the JVM. It should record the failure and return normally.
Exercise
Your comparator throws IndexOutOfBoundsException on its first call when reading a.get(ValueLayout.JAVA_INT, 0). The descriptor was built with plain ValueLayout.ADDRESS for both parameters. What is the cause and what is the fix?
Show answer
Pointers received in an upcall are zero-length segments unless the layout says what they point to. Reading 4 bytes from a zero-length segment is out of bounds. Declare the parameters with ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT), so the segments have length 4. The other option is reinterpret(4), but that is a restricted method and removes the bounds protection.