GraalVM Native Image: Compiling Your Java Application Ahead-of-Time
Jul 27, 2025 am 01:53 AMGraalVM Native Image converts Java applications into native executable files through AOT compilation, solving the problems of slow startup and high memory usage in the traditional JVM mode. 1. The startup speed is milliseconds, suitable for Serverless and microservices; 2. The memory usage is reduced by 30% to 70%; 3. The deployment package is smaller and there is no need to carry JVM; 4. The security is improved and the attack surface is reduced. Note when using: 1. Reflection, dynamic proxy, etc. need to be explicitly configured; 2. Resource files need to be included through resource-config.json; 3. Dynamic class loading is limited; 4. Some libraries that rely on ASM or dynamically generate bytecode are incompatible. Mainstream frameworks such as Spring Boot 3, Quarkus, and Micronaut are well supported and are suitable for cold boot-sensitive scenarios and are an important operating mode of Java in modern cloud native environments.
Java has long been known for being "written once, run everywhere", thanks to the JVM's instant compilation (JIT) and cross-platform bytecode execution. However, as the requirements for startup speed, memory footprint and cloud-native deployment efficiency become increasingly high, the traditional JVM model has begun to appear "cumbersome". GraalVM's Native Image technology is designed to solve these problems - it allows you to compile Java applications in advance (Ahead-of-Time, AOT) as a local executable.

What is Native Image?
Native Image is a tool provided by GraalVM that can directly compile Java bytecode (.class files or JARs) into platform-specific native executable files (such as ELF on Linux, Mach-O on macOS, PE on Windows). This process occurs before the application runs, that is, AOT compilation.
Unlike traditional JVM startup process:

- Traditional JVM : Java → Bytecode → JVM Explanation JIT Compilation → Machine Code (Runtime)
- Native Image : Java → Bytecode → Native Image Compilation → Native executable file (start, machine code)
The result is a separate binary file that no longer relies on JVM, starts very fast and has a lower memory footprint.
Why use Native Image?
1. Extremely fast startup speed
Native mirror startup time is usually in the millisecond level , which is especially suitable for cold start-sensitive scenarios such as Serverless (such as AWS Lambda), microservices, CLI tools, etc.

For example: It originally took 3 to 5 seconds to start a Spring Boot application, but it may only take 50ms after using Native Image.
2. Lower memory usage
Without the runtime overhead of JVM, off-heap memory is more controllable. Native mirrors usually use 30% to 70% less memory than equivalent JVM applications.
3. Smaller deployment packages
Although the generated binary files may be larger than JAR, they do not need to package the JVM , and the overall container image size is smaller, suitable for lightweight deployments.
4. Safer (some extent)
Without JVM, the attack surface is reduced; and the code has been determined at compile time, and dynamic behaviors such as reflection are limited, which helps with security auditing.
How to use Native Image?
Prerequisites
- Install GraalVM (recommended to use
graalvm-ce
orgraalvm-ee
) - Install
native-image
tool (viagu install native-image
)
# Example: JDK using GraalVM export JAVA_HOME=/path/to/graalvm gu install native-image
Compile a simple Java application
// HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, Native World!"); } }
Compilation steps:
javac HelloWorld.java native-image HelloWorld
Generate helloworld
executable file and run it directly:
./helloworld # Output: Hello, Native World!
Notes and restrictions
Native Image is not omnipotent. It has some key limitations, mainly due to the nature of AOT compilation:
1. Reflection, dynamic proxy, and JNI need to be explicitly configured
AOT cannot predict which classes will be used reflected when compiling, so the compiler must be told through the configuration file.
Common ways:
- Annotation with
@RegisterForReflection
- Provide
reflect-config.json
file
// reflect-config.json [ { "name": "com.example.MyClass", "methods": [ { "name": "<init>", "parameterTypes": [] } ] } ]
2. The resource file must be explicitly included
Configuration files, templates, international resources, etc. will not be automatically packaged and must be specified through resource-config.json
.
3. Dynamic class loading is limited
Class.forName()
, ClassLoader
dynamic loading classes are not available at runtime (unless known at compile time).
4. Some libraries are incompatible
For example: Groovy, JRuby, some frameworks that use ASM to generate bytecode dynamically, may have errors in Native Image.
Integration with mainstream frameworks
Fortunately, many modern Java frameworks already support Native Image:
- Spring Boot : Supported through Spring Native project (now integrated into Spring Boot 3)
- Quarkus : The default priority is to support native compilation, known as "born for cloud native"
- Micronaut : handles a lot of logic at compile time, naturally suitable for AOT
For example: To create a native application using Quarkus, just:
mvn quarkus:build -Dquarkus.package.type=native
Summarize
GraalVM Native Image allows Java applications to get rid of the "burden" of JVM and brings a qualitative leap in startup speed, memory efficiency and lightweight deployment. Although it has limitations on reflex and dynamic characteristics, these pain points are being gradually addressed as the ecosystem matures (especially the support of Spring Boot 3 Quarkus Micronaut).
If your application is:
- Microservice or Serverless function
- CLI Tools
- Scenarios that are sensitive to cold start
Then, it's worth trying Native Image. It is not about replacing the JVM, but provides Java with another operating mode that is more suitable for modern cloud environments .
Basically that's it - AOT compilation is no longer the "future", it has already started running in production.
The above is the detailed content of GraalVM Native Image: Compiling Your Java Application Ahead-of-Time. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Laravel's error and exception handling mechanism is based on the PHP exception system and Symfony component, and is managed uniformly by the App\Exceptions\Handler class. 1. Record exceptions through the report() method, such as integrating Sentry and other monitoring services; 2. Convert exceptions into HTTP responses through the render() method, supporting custom JSON or page jumps; 3. You can create custom exception classes such as PaymentFailedException and define their response format; 4. Automatically handle verification exception ValidationException, and manually adjust the error response structure; 5. Decide whether to display details based on the APP_DEBUG configuration.

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear
