GraalVM Native Image is a technology for compiling Java applications into native executables. 1. Fast startup and low memory footprint through AOT compilation; 2. Manually configure reflection, dynamic proxy and resources to avoid runtime errors; 3. Suitable for microservices, Serverless and CLI tools, but not suitable for scenarios where frequent dynamic loading of classes or rapid iterative development; 4. It is recommended to use frameworks such as Quarkus and Micronaut to simplify configuration; 5. It must be fully tested to ensure compatibility, so although it is not a universal alternative, it can significantly improve performance and resource efficiency in cloud-native scenarios.
Java Native Image with GraalVM is a way to compile Java applications ahead-of-time (AOT) into standalone native executes that start instantly and use fewer resources. It's not traditional Java execution — instead of running on the JVM with JIT compilation, your app becomes a self-contained binary.

Here's what you need to know to understand and use GraalVM Native Image effectively.
What Is Native Image?
Native Image is a technology from GraalVM that compiles Java bytecode ( .class
files) directly into a native machine executable — no JVM needed at runtime.

Instead of:
Java App → JVM → JIT Compilation → Execution
You get:

Java App → Native Image (AOT) → Native Binary → Direct Execution
This means:
- Faster startup — no JVM warm-up or class loading delay.
- Lower memory usage — no JIT compiler, GC overhead is reduced.
- Smaller footprint — ideal for containers and serverless environments.
But: you lose some dynamic features (like reflection, class loading at runtime) unless explicitly configured.
How Does It Work?
Native Image performs static analysis of your application at build time to determine:
- Which classes and methods are used
- What reflection is needed
- Which resources to include
Then it:
- Strips away unused code (like tree-shaking in JavaScript)
- Converts the remaining bytecode into native machine code
- Embeds a minimum runtime (including garbage collector)
The result is a single binary you can run like:
./my-app
No java -jar
, no JVM arguments, no classpath.
When Should You Use It?
? Good for:
- Microservices (fast startup = better scaling)
- Serverless functions (AWS Lambda, Google Cloud Functions)
- CLI tools (near-instant response)
- Environments with limited memory
? Not ideal for:
- Apps that heavily use dynamic class loading
- Applications relying on deep reflection (unless configured properly)
- Rapid development cycles (build time is slow — 5–10 minutes common)
Basic Usage Example
Install GraalVM and enable Native Image:
# Using SDKMAN (Linux/macOS) sdk install java 21.0.2-graal gu install native-image
Write a simple Java app:
// HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, Native World!"); } }
Compile and build native image:
javac HelloWorld.java native-image HelloWorld
Run it:
./helloworld # No JVM needed
Handling Reflection, Proxies, and Resources
Native Image doesn't automatically detect:
- Reflection (
Class.forName
,Method.invoke
) - Dynamic proxies
- JNI
- Resources (files in
src/main/resources
)
You must tell it what to include via:
-
reflect-config.json
— list classes used via reflection -
proxy-config.json
— for dynamic proxies -
resource-config.json
— to include specific files
Or use the @RegisterForReflection
annotation (in Quarkus or Micronaut):
@RegisterForReflection public class MyModel { ... }
Alternatively, run your app with -Dnative-image.enable-reachable-types=true
or use trace configuration via the --initialize-at-build-time
and agent:
# Run with agent to generate config java -agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image HelloWorld
Then rebuild — the agent records what your app uses dynamically and generates config files automatically.
Build-Time vs. Run-Time Initialization
By default, classes are initialized at run time . But you can reduce startup time by initializing some at build time :
--initialize-at-build-time=com.mypackage.OptimizedAtBuildTime
?? Only safe for classes without side effects or external dependencies (like network, files).
Performance Trade-offs
Aspect | JVM (HotSpot) | Native Image |
---|---|---|
Startup time | Slower (seconds) | Milliseconds |
Memory usage | Higher | Lower (~50% less) |
Peak throughput | Higher (JIT optimized) | Slightly lower |
Build time | Fast | Slow (minutes) |
Debugging | Easy | Harder (no JIT, limited tooling) |
So: great for cold starts, less ideal for long-running apps needing peak performance.
Frameworks That Support Native Image
Some frameworks are optimized for it:
- Quarkus — designed for native from the start
- Micronaut — minimal reflection, build-time injection
- Spring Native — experimental support in Spring Boot
These handle most configuration automatically.
Common Pitfalls
- Missing reflection config →
ClassNotFoundException
at runtime - Dynamic resource loading → files not included
- Using
System.getProperty()
in static init → returnsnull
if property not set at build time - Too much build-time init → breaks if code depends on runtime environment
Always test your native binary thoroughly.
Summary
GraalVM Native Image turns Java apps into fast, lightweight executables — perfect for cloud-native use cases. It requires careful configuration, especially around reflection and dynamic features, but frameworks like Quarkus make it much easier.
It's not a drop-in replacement for all Java apps, but when used right, it delivers dramatic improvements in startup and footprint.
Basically: if you're building microservices or serverless functions, it's worth trying. Just don't expect it to work perfectly out of the box.
The above is the detailed content of Java Native Image with GraalVM Explained. 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.

Full screen layout can be achieved using Flexbox or Grid. The core is to make the minimum height of the page the viewport height (min-height:100vh); 2. Use flex:1 or grid-template-rows:auto1frauto to make the content area occupy the remaining space; 3. Set box-sizing:border-box to ensure that the margin does not exceed the container; 4. Optimize the mobile experience with responsive media query; this solution is compatible with good structure and is suitable for login pages, dashboards and other scenarios, and finally realizes a full screen page layout with vertical centering and full viewport.

Selecting the Java SpringBoot React technology stack can build stable and efficient full-stack web applications, suitable for small and medium-sized to large enterprise-level systems. 2. The backend uses SpringBoot to quickly build RESTfulAPI. The core components include SpringWeb, SpringDataJPA, SpringSecurity, Lombok and Swagger. The front-end separation is achieved through @RestController returning JSON data. 3. The front-end uses React (in conjunction with Vite or CreateReactApp) to develop a responsive interface, uses Axios to call the back-end API, and ReactRouter

Use performance analysis tools to locate bottlenecks, use VisualVM or JProfiler in the development and testing stage, and give priority to Async-Profiler in the production environment; 2. Reduce object creation, reuse objects, use StringBuilder to replace string splicing, and select appropriate GC strategies; 3. Optimize collection usage, select and preset initial capacity according to the scene; 4. Optimize concurrency, use concurrent collections, reduce lock granularity, and set thread pool reasonably; 5. Tune JVM parameters, set reasonable heap size and low-latency garbage collector and enable GC logs; 6. Avoid reflection at the code level, replace wrapper classes with basic types, delay initialization, and use final and static; 7. Continuous performance testing and monitoring, combined with JMH

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.

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;

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