Sub topic 9
Garbage collection and memory in a native image
A native executable still needs a garbage collector. It does not run on the JVM, so it carries its own memory manager, called Substrate VM, inside the executable. This chapter covers how that runtime lays out memory, which collectors you can choose, and how to size the heap. It also covers the settings that matter in containers.
This chapter assumes you can build a native image with native-image (covered earlier) and that you know what a heap, a young generation and a garbage collection pause are.
What changes compared with the JVM
On a JVM, memory use has several parts: the Java heap, metaspace for class metadata, the JIT compiler's code cache, and the compiler's own working memory. A native image removes or shrinks most of these.
| Memory area | HotSpot JVM | Native image |
|---|---|---|
| Compiled code | JIT-compiled at run time into a code cache | Compiled ahead of time and stored in the executable's text section |
| Class metadata | Loaded into metaspace at run time | Mostly resolved at build time. There is no class loading of application classes. |
| JIT compiler memory | Present while the application warms up | Absent |
| Pre-initialized objects | Created when classes initialize at run time | Written into the image heap at build time |
| Java heap | Managed by G1, Parallel, ZGC and others | Managed by Serial GC, G1 or Epsilon |
| Thread stacks | Per thread | Per thread |
This is why a native image usually has a smaller resident set size (RSS, the physical memory a process actually holds) right after startup. The saving is mostly fixed overhead. A native image does not shrink the objects your program allocates.
The image heap and the run-time heap
A native image has two kinds of heap objects.
The image heap is a snapshot of objects created while the image was built. Static fields of classes that were initialized at build time, interned strings, and constants all end up there. The snapshot is stored in the executable file and mapped into memory when the process starts. Nothing has to be rebuilt at startup, which is part of why startup is fast.
The run-time heap holds everything your program allocates after main starts. The garbage collector manages it and reclaims objects that are no longer reachable.
The link to class initialization matters here. If a class is initialized at build time, the objects its static fields reference become part of the image heap. That makes the executable larger but removes the work at startup. If the class is initialized at run time, those objects are allocated on the run-time heap on every start. The chapter on build-time and run-time initialization covers how to choose.
Choosing a garbage collector
You pick the collector at build time with the --gc option. The collector is compiled into the executable. You cannot switch it at run time as you can with -XX:+UseG1GC on a JVM.
| Option | Collector | Availability | Typical use |
|---|---|---|---|
| `--gc=serial` (default) | Serial GC: generational, single-threaded, stop-the-world | All GraalVM editions and platforms | Small heaps, containers with one or two CPUs, short-running programs |
| `--gc=G1` | Garbage-First: generational, region-based, concurrent phases | Oracle GraalVM, on selected platforms such as Linux on x64 and AArch64 | Larger heaps and workloads that need shorter pauses |
| `--gc=epsilon` | Epsilon: allocates but never collects | Recent GraalVM versions. It may need an experimental-options flag in some releases. | Very short jobs and tests where the heap is never exhausted |
Check your GraalVM version's documentation before relying on G1 or Epsilon. Support depends on the edition, the operating system and the CPU architecture.
Build with an explicit collector like this:
native-image --gc=serial -jar app.jar -o appSerial GC
Serial GC is a generational collector. New objects go into a young generation. A young collection copies surviving objects out of it, and objects that survive long enough are promoted to the old generation. When the old generation fills up, a full collection runs. All application threads stop during each collection, and the collector uses one thread.
The pauses are short for small heaps and grow with the amount of live data. For a service with a heap of a few hundred megabytes in a small container, this is often acceptable. The collector also has a small footprint and no background threads.
G1
G1 divides the heap into regions and runs some of its work concurrently with the application. It needs more memory for its own bookkeeping and uses several threads, but it can keep pauses shorter on large heaps. If you choose G1 for a native image, measure it against Serial GC, because a small heap in a small container may not benefit.
Epsilon
Epsilon hands out memory and never reclaims it. When the heap is full, the process fails with an OutOfMemoryError. This suits a command-line tool that allocates a known, small amount and exits, or a benchmark where you want to remove collection cost. It is a poor fit for any long-running service.
Sizing the heap
The collector's heap limits can be set when you start the executable, using options similar to the JVM's:
| Option | Meaning |
|---|---|
| `-Xmx256m` | Maximum heap size |
| `-Xms64m` | Initial heap size |
| `-Xmn32m` | Young generation size |
| `-XX:+PrintGC` | Print a line for each collection |
| `-XX:+VerboseGC` | Print more detail about each collection |
Note that the -XX: options use the Native Image runtime's own flag set. Only a subset of HotSpot's flags exists, and unknown flags cause an error at startup. Your executable must also accept these options. By default it does, but if you built with -H:-ParseRuntimeOptions they are treated as ordinary program arguments.
If you do not set a maximum, the default is a percentage of physical memory, 80% in the current implementations. In a container, the runtime reads the container's memory limit, so the heap limit is derived from that, not from the host's RAM. Still, set -Xmx explicitly in production. It makes behavior predictable and leaves room for thread stacks, the image heap and other non-heap memory.
You can also bake defaults into the executable at build time with the -R: prefix:
native-image --gc=serial -R:MaxHeapSize=256m -jar app.jar -o appA command-line -Xmx at run time overrides the baked-in value, so this is a safe default for users who start the program without options.
Observing the collector
The following program allocates short-lived arrays while keeping a small number of them alive. This gives the collector both garbage and survivors to deal with.
import java.util.ArrayList;
import java.util.List;
public class Allocator {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.println("max heap MB: " + rt.maxMemory() / (1024 * 1024));
List<byte[]> retained = new ArrayList<>();
long checksum = 0;
for (int i = 0; i < 200_000; i++) {
byte[] block = new byte[16 * 1024];
block[0] = (byte) i;
checksum += block[0];
if (i % 2_000 == 0) {
retained.add(block);
}
}
System.out.println("retained blocks: " + retained.size());
System.out.println("used heap MB: "
+ (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024));
System.out.println("checksum: " + checksum);
}
}Build and run it with a small heap and collection logging:
javac Allocator.java
native-image --gc=serial Allocator
./allocator -Xmx64m -XX:+PrintGCThe program allocates about 3 GB in total across the loop, but it keeps only 100 blocks of 16 KB each, about 1.6 MB. With a 64 MB limit it still finishes, because the collector reclaims the rest. You should see many young collections in the PrintGC output. The exact lines depend on your GraalVM version, so look for the pattern, not the text: frequent short young collections and few or no full collections.
Now change the program so that it retains every block, for example by calling retained.add(block) on every iteration. With -Xmx64m it fails with java.lang.OutOfMemoryError. That confirms the limit is enforced and that the collector cannot free objects that are still reachable.
Memory in containers
Native images are often deployed in containers with a fixed memory limit. A few points matter there.
- The heap is not the whole process. RSS also includes the image's code and image heap, thread stacks, and native allocations. Set
-Xmxbelow the container limit, and leave headroom. - Serial GC does not use extra threads for collection, so a one-CPU container has no contention from the collector. G1 starts several threads and works best with more than one CPU.
- If the process is killed with no Java exception and exit code 137, the operating system's out-of-memory killer ended it. The heap limit was too close to the container limit, or non-heap memory grew.
- The memory the process holds does not always shrink after a collection. Check RSS over time, not only the heap figures that
PrintGCshows.
Common mistakes
- Assuming JVM flags work. Options like
-XX:+UseG1GC,-XX:MaxMetaspaceSizeor-XX:+UseStringDeduplicationdo not exist in a native image. Choose the collector with--gcat build time. - Leaving the heap size unset in production. The 80% default can be too large when other processes share the machine.
- Expecting a native image to use less memory for the data itself. It saves on JVM overhead and warm-up memory. A program that holds 2 GB of live objects still needs about 2 GB of heap.
- Moving large amounts of data into the image heap by initializing classes at build time. This makes the executable bigger and the image slower to build, and the data takes address space in every process that starts from it.
- Choosing G1 without measuring. On small heaps, Serial GC often has a smaller footprint and comparable pause times.
Exercise
A native image running in a container with a 512 MB memory limit is killed with exit code 137 and no Java stack trace. The application was started without any -Xmx option. What is the likely cause, and what would you change?
Show answer
The operating system's out-of-memory killer ended the process, which is different from a Java OutOfMemoryError. With no -Xmx, the heap can grow up to a default share of memory (80% of the available memory), and the process also uses memory for the image heap, code, thread stacks and native allocations, so total use can exceed the container limit. Set an explicit maximum heap well below the limit, for example -Xmx320m, and leave headroom for non-heap memory. Then check RSS under load to confirm the margin is enough.
Exercise
You need a native image for a command-line tool that processes a small file and exits in under a second, allocating about 20 MB in total. Which --gc option could remove collection cost entirely, and why would it be a bad choice for a web service?
Show answer
--gc=epsilon. It allocates memory but never collects, so a program with a small, known allocation total never pays for a collection. A web service allocates continuously for as long as it runs, so the heap would fill and the process would fail with an OutOfMemoryError.
Exercise
What is the difference between the image heap and the run-time heap, and how does initializing a class at build time affect them?
Show answer
The image heap is a snapshot of objects created during the build and stored in the executable. It is mapped into memory at startup and needs no allocation work. The run-time heap holds objects the program allocates after it starts, and the garbage collector manages it. When a class is initialized at build time, the objects its static fields reference go into the image heap, which makes the executable larger but avoids creating them on each start. When it is initialized at run time, those objects are allocated on the run-time heap on every start.