How Java 19’s Foreign Function and Memory API Simplifies Calling Native APIs

Info

This post is part of a blog post series titled 6 New Features in Java 19 That Make Your Life Easier.

Note

This is a preview feature. In order to use it, compile the program with javac --release 19 --enable-preview Main.java and run it with java --enable-preview Main. More details about using preview features in your project can be found here.

The Foreign Function and Memory API (FFM API) is designed to allow developers to access data and code outside of the Java Runtime. The API allows accessing native libraries and native data without having to use JNI.

The main goals of this API are:

  • Simplicity: To replace the Java Native Interface (JNI) with a more powerful, pure Java-based development model.
  • Performance: In terms of performance, the new API should be able to run as fast or even faster than existing APIs.
  • Generality: It should be possible to use the API for different memory types (e.g. native memory, heap memory, persistent memory), but also different platforms (e.g. 32-bit x86). It should also be possible to access functions written in languages other than C (e.g. C++, Fortran).

Whenever Java code interacts with native code, there is a possibility that the integrity of the Java platform will be compromised. Linking a C function with a precompiled library is a tricky operation because the Java runtime cannot guarantee that the signature of the C function matches the expectations of the Java code. There are other examples as well. In all cases, there is a risk of low-level failures, such as segmentation faults, which end in a crash of the Java Virtual Machine. Such failures cannot be caught by the Java Runtime or Java code.

This is exactly the scenario, where the FFM API can help: Most of the FFM API is safe by design. Many scenarios that require the use of JNI can now be implemented by calling the FFM API, which cannot compromise the Java platform. In short, Java code that uses the FFM API cannot crash the Java Virtual Machine.

References

Leave a Comment

Your email address will not be published. Required fields are marked *