Sources for This Summary:
- https://www.oracle.com/java/graalvm/what-is-graalvm/
- https://www.graalvm.org/latest/reference-manual/native-image/
- https://www.oracle.com/a/ocom/docs/graalvm-enterprise-white-paper.pdf
- https://www.graalvm.org/latest/reference-manual/native-image/basics/
So What Is It?
GraalVM began in 2011 as a research project at Oracle Labs, with the goal of creating a high-performance runtime platform that could run multiple programming languages.
At the heart of GraalVM is the highly optimizing GraalVM compiler, which is used as the just-in-time (JIT) compiler for the Java Virtual Machine (JVM), or by GraalVM Native Image to ahead-of-time compile Java bytecode into native machine code. GraalVM's Truffle language implementation framework works with the GraalVM compiler to run JavaScript, Python, Ruby, and other supported languages on the JVM with standout performance.
- GraalVM includes an advanced just-in-time compiler (JIT) called the GraalVM JIT compiler. The JVM uses it to create platform-specific machine code from Java bytecode while an application runs.
- It also has a Native Image utility that can ahead-of-time compile (AOT) Java bytecode and produce native executables for applications that need to start almost instantly and use very few memory resources.
- GraalVM also supports polyglot interoperability through the Truffle language implementation framework. Programs written in Truffle-supported languages can use polyglot libraries. For example, a JavaScript program can call a Ruby method and share values without making copies. When running on the JVM, Truffle works with the GraalVM compiler to compile supported languages to native machine code for peak performance, just like Java. (https://www.graalvm.org/latest/graalvm-as-a-platform/language-implementation-framework/)
Features
Lower resource usage
Native executables use only a fraction of memory and CPU resources required by a JVM, which improves utilization and reduces costs.
More secure
Native executables contain only the classes, methods, and fields that your application needs, which reduces attack surface area.
Faster startup
Native executables compiled ahead of time start up instantly and require no warmup to run at peak performance.
Smaller package size
Native executables are small and offer a range of linking options that make them easy to deploy in minimal container images.
Strong framework support
Popular frameworks such as Spring Boot, Micronaut, Helidon, and Quarkus provide first-class support for GraalVM.
Cloud platform support
SDKs from leading cloud platforms such as AWS, Microsoft Azure, GCP, and Oracle Cloud Infrastructure integrate and support GraalVM.
Use Cases
Boost performance and extend existing Java applications The JIT compiler uses an advanced optimizer to increase peak throughput. It also optimizes memory consumption by minimizing object allocation, reducing time spent in garbage collection. Running GraalVM in JIT mode can improve performance by up to 50%. That can free up memory faster and lower IT costs.
- Build cloud native applications
Oracle GraalVM's Native Image utility ahead-of-time compiles bytecode Java applications into machine binaries. Compared with running on the JVM, native executables start nearly 100 times faster and consume 5 times less memory.
HelloWorld run comparison
- Develop multilanguage programs and improve productivity
You can run Java and other languages such as JavaScript on the JVM with excellent performance. Oracle NetSuite's SuiteScript is an extension language that lets end users customize applications running on NetSuite. Oracle GraalVM enabled NetSuite to embed a Truffle-based JavaScript runtime that compiles JavaScript to machine code that runs 4 times faster than SuiteScript on the JVM.
Native Executable? Just Run the Binary?
Who turns Java into a binary executable? Native-Image
How does it do that?
native-image processes your application classes and other metadata to create a binary for a specific operating system and architecture.
First, the
native-imagetool performs static analysis of your code to determine the classes and methods that are reachable when your application runs. Second, it compiles classes, methods, and resources into a binary. This entire process is called build time to clearly distinguish it from the compilation of Java source code to bytecode.
The native-image tool processes your application classes and other metadata to create a binary for a specific operating system and architecture.
First, the native-image tool performs static analysis on your code to determine which classes and methods are reachable when your application runs. Second, it compiles classes, methods, and resources into a binary. This entire process is called build time, to clearly distinguish it from compiling Java source code into bytecode.
Let's Try It
HelloWorld
Build Time vs Run Time
During image build, the native image may execute user code. This code can have side effects, such as writing a value to a class's static field. We say this code runs at build time. The values this code writes to static fields are stored in the image heap. Run time refers to the code and state of the binary while it executes.
In Java, when a class is first used, it is initialized. Every Java class used at build time is said to be build-time initialized. Note that merely loading a class does not necessarily initialize it. The static initializer of a build-time initialized class runs on the JVM that is running the image build.
If a class is initialized at build time, its static fields are saved in the generated binary. At runtime, the first use of such a class does not trigger class initialization.
A More Complex Example
Native Image Heap
It contains the following three parts:
Objects created during the image build that are reachable from application code.
Objects created during the image build that application code can reach.
java.lang.Classobjects of classes used in the native image.The class objects for classes used in the native image.
Object constants embedded in method code.
Object constants embedded in method code.
class ReflectiveAccess {
public Class<Foo> fetchFoo() throws ClassNotFoundException {
return Class.forName("Foo");
}
}
Static Analysis
Static analysis is the process of determining which program elements—classes, methods, and fields—an application uses. These elements are also called reachable code. The analysis itself has two parts:
- Scan method bytecode to find other elements reachable from it.
- Scan root objects in the native image heap (that is, static fields) to determine which classes can be reached from them. It starts from the application entry point (the
mainmethod). Newly discovered elements are scanned iteratively until further scanning no longer changes reachability.
The final image contains only reachable elements. Once a native image is built, you cannot add new elements at runtime—for example, through class loading. We call this constraint the closed-world assumption.
Compiling a JAR
Directory
| src
| --com/
| -- example
| -- App.java
Code
Compile Commands
1. javac -d build src/com/example/App.java
2. jar --create --file App.jar --main-class com.example.App -C build .
3. native-image -jar App.jar
Tips:
The default behavior of native-image is aligned with the java command which means you can pass the -jar, -cp, -m options to build with Native Image as you would normally do with java. For example, java -jar App.jar someArgument becomes native-image -jar App.jar and ./App someArgument.
Native Image Build Output
- Build Stages
- Resource Usage Statistics
- Machine-Readable Build Output
For more details, see: https://www.graalvm.org/latest/reference-manual/native-image/overview/BuildOutput/
Tips: RSS: In computing, resident set size (RSS) is the portion of memory (in kilobytes) occupied by a process in main memory (RAM). The rest of the memory it occupies lives in swap space or the file system—either because part of the memory has been paged out or because part of the executable has not been loaded.
What About Projects with Lots of Third-Party Libraries?
Reachability Metadata
Build-time analysis can identify some cases of dynamic class loading, but it cannot always fully predict every use of the Java Native Interface (JNI), Java Reflection, dynamic proxy objects, or classpath resources. To handle these dynamic Java features, you need to give the analysis details about the classes that use reflection, proxies, and similar features, or about which classes will be loaded dynamically.
To make sure these elements are included in the native binary, you should provide reachability metadata (called metadata below) to the native-image builder. Providing reachability metadata to the builder also helps ensure seamless runtime compatibility with third-party libraries.
Two approaches:
- Compute metadata in your code during native binary build time and store the required elements in the native binary's initial heap.
Provide JSON files stored in the project directory
META-INF/native-image/<group.id>/<artifact.id>
Naming format:
Each dynamic Java feature that needs metadata has a corresponding JSON file named <feature>-config.json. The JSON file consists of entries that tell Native Image which elements to include. For example, Java reflection metadata is specified in reflect-config.json.
Metadata Types:
- Java Reflection
- JNI
- Resources and Resource Bundles
- Dynamic JDK Proxies
- Serialization
- Predefined Classes
For details on interacting with each metadata type, see: https://www.graalvm.org/latest/reference-manual/native-image/dynamic-features/
Tracing Agent
Writing it by hand too much trouble? GraalVM provides a Tracing Agent.
- -agentlib:native-image-agent=....
- Inject the agent through the process environment.
export JAVA_TOOL_OPTIONS="-agentlib:native-image-agent=config-output-dir=/path/to/config-output-dir-{pid}-{datetime}/"
To learn more about metadata, ways to provide it, and supported metadata types, see Reachability Metadata. To automatically collect metadata for your application, see Automatic Collection of Metadata.
I Want It to Work Out of the Box!
Embrace Spring Boot 3: https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html
Example: A Simple CRUD Spring Boot 3 App
Here's the Git link
Data Comparison
- JIT vs NativeImage
Performance of Spring Petclinic with Oracle GraalVM Native Image and GraalVM CE with C2 JIT. The benchmarking experiment ran the latest Spring Petclinic on Oracle X5–2 servers (Intel Xeon E5–2699 v3), restricting the workload to 16 CPUs and setting a maximum heap size of 1GB.
- Performance Benchmark Comparison
Performance of Spring Petclinic with Oracle GraalVM Native Image and GraalVM CE with C2 JIT. The benchmarking experiment ran the latest Spring Petclinic on Oracle X5–2 servers (Intel Xeon E5–2699 v3), restricting the workload to 16 CPUs and setting a maximum heap size of 512MB.
- Throughput Comparison