Sub topic 3
Garbage Collection and Memory in a Native Image
This chapter assumes that you can compile Java, use JARs, and understand basic JVM heap and garbage-collection terms.
Runtime memory
A Native Image executable contains compiled application code and a native runtime. It still has a managed heap, so garbage collection remains necessary. The available collectors depend on the GraalVM distribution and version. A simple collector often favors low footprint, while a more concurrent collector may favor throughput at the cost of memory.
Set heap limits with familiar options:
./app -Xms16m -Xmx256mThe process's resident memory can exceed the Java heap. It also includes compiled code, thread stacks, metadata, direct buffers, and memory allocated by native libraries.
Comparing deployment choices
Native images usually start faster and use less memory at idle because they do not start a JVM or compile methods during execution. JVM applications often achieve higher peak throughput after warm-up because the JIT compiler can optimize using live runtime data. Native-image builds take longer and consume more build resources.
| Concern | Native Image | JVM |
|---|---|---|
| Startup | Usually fast | Usually slower |
| Idle footprint | Usually smaller | Usually larger |
| Peak throughput | May be lower | Often higher after warm-up |
| Build time | Longer | Shorter |
Profile the real workload before choosing. A short-lived HTTP service may benefit from fast startup, while a long-running batch job may prefer JVM throughput.
Containers and linking
Build the executable in an environment compatible with the target. A Linux executable may depend on glibc, or it can target a musl-based environment when supported. A multi-stage container keeps the native-image toolchain out of the final image.
FROM ghcr.io/graalvm/native-image:latest AS build
WORKDIR /src
COPY . .
RUN native-image -jar app.jar -o app
FROM alpine:latest
COPY --from=build /src/app /app
ENTRYPOINT ["/app"]Common failures
UnsupportedFeatureExceptionoften identifies an unsupported API or dynamic behavior.- A missing class, resource, or constructor usually requires reachability metadata.
- A process killed by the operating system usually needs a smaller heap, fewer threads, or more container memory.
- Compare native and JVM behavior with the same workload and limits.
Framework support
Spring Boot, Quarkus, and Micronaut provide native-image configuration and build integrations. They can supply metadata for framework features such as reflection and proxies. Verify supported libraries and test production-like paths, because application-specific dynamic behavior can still require configuration.
Exercise
Why can a native-image process exceed its -Xmx limit?
Show answer
-Xmx limits the managed heap, but the process also uses memory for code, stacks, metadata, direct buffers, and native libraries.