Foreign Function & Memory API
- Java course
- Expert
- Lesson 29/46
- 5 min
Learn modern native calls with the Java 21 FFM API.
Foreign Function & Memory API
The FFM API (Foreign Function & Memory API, Java 21+) is a modern alternative to JNI. It lives in the java.lang.foreign package. Linker.nativeLinker() gives a native linker, SymbolLookup finds symbols, MemorySegment models off-heap memory and MethodHandle performs the call.
It is safer than JNI: memory access is bounds-checked and the lifetime is managed with an Arena. For new code FFM API is recommended over JNI.
Memory with MemorySegment
MemorySegment represents an off-heap memory region. It is allocated with an Arena; when the arena closes the memory is freed automatically. This reduces the manual malloc/free risks of JNI.
A native function is obtained as a MethodHandle and called with invoke. Data is read and written on a MemorySegment; bounds checking catches errors early.
Practice Prepare the linker with the FFM API
Add import java.lang.foreign.Linker;. In Main's main method create the linker with Linker linker = Linker.nativeLinker(); and print System.out.println("linker ready");.
Starter code
// Import Linker from the java.lang.foreign package
// Main: create the native linker and print linker readySample solution
import java.lang.foreign.Linker;
public class Main {
public static void main(String[] args) {
Linker linker = Linker.nativeLinker();
System.out.println("linker ready");
}
}Expected output
linker ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the Linker creation
Linker linker = Linker.____;
Linker linker = Linker.nativeLinker();
Explanation: Linker.nativeLinker() returns the native linker.
2 Which package holds the FFM API?
- java.lang.native
- java.lang.foreign Correct answer
- java.foreign
- javax.jni
Explanation: The FFM API lives in java.lang.foreign.
3 Match the FFM elements
| Term | Meaning |
|---|---|
Linker |
Native call bridge |
SymbolLookup |
Symbol lookup |
MemorySegment |
Off-heap memory |
Arena |
Memory lifetime |