JVM memory and garbage collection
The JVM divides memory into areas with different jobs and reclaims unused objects automatically. Knowing how that works explains why most garbage is nearly free, why some allocations cost much more than their size suggests, and what OutOfMemoryError really means. This page explains the memory areas and the generational design, then reads the JVM's own pools, counters and GC notifications while programs allocate, and runs one workload under four collectors.
Contents
How the JVM organizes and reclaims memory
A running JVM uses several separate areas of memory:
- The heap holds every object and array. Its maximum is set with
; by default it is a quarter of the machine's (or container's) memory, and it starts at a sixty-fourth.-Xmx - Metaspace holds class metadata, outside the heap, and grows as classes are loaded. It replaced the "permanent generation" in Java 8.
- The code cache holds machine code produced by the JIT compiler.
- Each thread has its own stack for method frames, outside the heap; see
memory management basics . - Direct memory backs direct
s and is limited byByteBuffer .-XX:MaxDirectMemorySize
The garbage collector reclaims heap objects that are no longer reachable. All of HotSpot's main collectors rely on the generational hypothesis: most objects die young. New objects are allocated in a young area (eden). A young collection copies the few survivors out and treats the rest of eden as free, so its cost depends on the number of live objects, not on the amount of garbage. Objects that survive several young collections are promoted to the old generation, which is collected less often.
| Collector | Flag | History and default | Pauses | Best for |
|---|---|---|---|---|
| Serial | -XX:+UseSerialGC | Selected by default on small machines (1 CPU or under about 1.8 GB) up to JDK 26; since JDK 27, G1 is the default everywhere (JEP 523) | All work in pauses, one thread | Small heaps, one CPU, short-lived tools |
| Parallel | -XX:+UseParallelGC | The default on server machines until G1 replaced it in Java 9 | All work in pauses, many threads | Batch jobs that care about total throughput |
| G1 | -XX:+UseG1GC | Java 7; default since Java 9 (JEP 248) | Short pauses with a target, concurrent marking | Most applications |
| ZGC | -XX:+UseZGC | Production in Java 15; generational in Java 21 (JEP 439) | Under a millisecond, almost all work concurrent | Large heaps and latency-sensitive services |
| Shenandoah | -XX:+UseShenandoahGC | Production in Java 15 | Very short, concurrent compaction | Like ZGC; included in many OpenJDK builds |
| Epsilon | -XX:+UseEpsilonGC | Java 11 (experimental) | None: it never collects | Measuring allocation, very short programs |
The programs ran on JDK 21 on a 2-CPU Linux machine; their JVM flags are shown with each output. Generational ZGC became the default ZGC mode in Java 23, so on JDK 21 the -XX:+UseZGC
The memory pools of a running JVM
The java.lang.management
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.util.Comparator;
public class MemoryAreas {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.printf("heap: max %d MB, committed %d MB%n",
rt.maxMemory() >> 20, rt.totalMemory() >> 20);
System.out.println("memory pools (sorted by type, then name):");
ManagementFactory.getMemoryPoolMXBeans().stream()
.sorted(Comparator.comparing((MemoryPoolMXBean p) -> p.getType().toString())
.thenComparing(MemoryPoolMXBean::getName))
.forEach(p -> System.out.printf(" %-34s %s%n", p.getName(), p.getType()));
System.out.println("collectors:");
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
System.out.println(" " + gc.getName());
}
}
}
Output (run with -XX:+UseG1GC -Xmx256m
heap: max 256 MB, committed 96 MB
memory pools (sorted by type, then name):
G1 Eden Space Heap memory
G1 Old Gen Heap memory
G1 Survivor Space Heap memory
CodeHeap 'non-nmethods' Non-heap memory
CodeHeap 'non-profiled nmethods' Non-heap memory
CodeHeap 'profiled nmethods' Non-heap memory
Compressed Class Space Non-heap memory
Metaspace Non-heap memory
collectors:
G1 Young Generation
G1 Concurrent GC
G1 Old Generation
- The heap may grow to 256 MB, but only 96 MB were committed at start: the JVM reserves the address space and asks the operating system for real memory as needed. The committed size depends on the machine's memory.
- G1 shows three heap pools: Eden, Survivor and Old Gen. In G1 these are not fixed areas but sets of equal-sized regions, so the young generation can shrink and grow between collections.
- The non-heap pools are the three segments of the code cache, Metaspace and the compressed class space, where class metadata referenced from object headers lives.
- G1 registers three collector beans: young collections, the concurrent marking cycle, and full collections ("Old Generation"), which a healthy G1 application should almost never see.
Young collections: garbage is nearly free
The program allocates about 2 GB of 1 KB arrays that die immediately, in a 256 MB heap, then keeps 100 MB alive and releases it again. The counts and sizes are printed as checks, since exact numbers vary from run to run.
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
public class YoungGc {
static long collections() {
long total = 0;
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
total += gc.getCollectionCount();
}
return total;
}
static volatile byte[] sink; // stops the JIT from optimizing the allocation away
public static void main(String[] args) {
long before = collections();
long garbage = 0;
for (int i = 0; i < 2000000; i++) {
byte[] temp = new byte[1024]; // short-lived: dies right away
sink = temp;
garbage += temp.length;
}
System.out.println("allocated " + (garbage >> 20) + " MB of short-lived arrays");
long cycles = collections() - before;
System.out.println("GC cycles during that: more than 10: " + (cycles > 10));
// Long-lived objects survive and get promoted to the old generation
List<byte[]> kept = new ArrayList<>();
for (int i = 0; i < 100; i++) {
kept.add(new byte[1024 * 1024]); // 100 MB that stays reachable
}
Runtime rt = Runtime.getRuntime();
long used = (rt.totalMemory() - rt.freeMemory()) >> 20;
System.out.println("after keeping 100 MB: heap used is at least 100 MB: " + (used >= 100)
+ " (max " + (rt.maxMemory() >> 20) + " MB)");
kept.clear();
System.gc();
long after = (rt.totalMemory() - rt.freeMemory()) >> 20;
System.out.println("after clear + System.gc(): used under 10 MB: " + (after < 10));
}
}
Output (run with -XX:+UseG1GC -Xmx256m
allocated 1953 MB of short-lived arrays
GC cycles during that: more than 10: true
after keeping 100 MB: heap used is at least 100 MB: true (max 256 MB)
after clear + System.gc(): used under 10 MB: true
- Allocating 1,953 MB in a 256 MB heap needed more than 10 collections, but each was cheap: almost nothing in eden was alive, so there was almost nothing to copy. Allocation itself is a pointer bump in a thread-local buffer (TLAB), a few instructions.
- The 100 MB that stayed reachable were really kept, and after
and a full collection the heap use dropped to a few megabytes.clear() - The practical rule: short-lived objects are cheap, long-lived objects are cheap, and objects that live just long enough to be promoted and then die are the expensive ones, because they fill the old generation.
Why a collection happens: causes and humongous objects
Every collector bean sends a JMX notification after each collection, with its action and its cause. The program listens to them while it runs three phases: small arrays, 600 KB arrays in a G1 heap whose regions are fixed at 1 MB, and an explicit System.gc()
import com.sun.management.GarbageCollectionNotificationInfo;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import javax.management.NotificationEmitter;
import javax.management.openmbean.CompositeData;
public class GcCauses {
static final Map<String, Integer> EVENTS = new ConcurrentHashMap<>();
static volatile Object sink;
public static void main(String[] args) throws InterruptedException {
// Every collector bean emits a notification after each collection
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
((NotificationEmitter) gc).addNotificationListener((n, handback) -> {
if (n.getType().equals(GarbageCollectionNotificationInfo
.GARBAGE_COLLECTION_NOTIFICATION)) {
var info = GarbageCollectionNotificationInfo.from(
(CompositeData) n.getUserData());
EVENTS.merge(info.getGcAction() + " / " + info.getGcCause(), 1, Integer::sum);
}
}, null, null);
}
phase("1. 2 GB of 1 KB arrays", () -> {
for (int i = 0; i < 2000000; i++) {
sink = new byte[1024];
}
});
phase("2. 600 KB arrays, region size 1 MB", () -> {
for (int i = 0; i < 2000; i++) {
sink = new byte[600 * 1024]; // over half a region: humongous
}
});
phase("3. System.gc()", System::gc);
}
static void phase(String name, Runnable work) throws InterruptedException {
EVENTS.clear();
work.run();
Thread.sleep(200); // notifications are asynchronous
System.out.println(name + ":");
new TreeMap<>(EVENTS).forEach((k, v) -> System.out.println(" " + k
+ (v > 1 ? " (several times)" : " (once)")));
}
}
Output (run with -XX:+UseG1GC -Xmx256m -XX:G1HeapRegionSize=1m
1. 2 GB of 1 KB arrays:
end of minor GC / G1 Evacuation Pause (several times)
2. 600 KB arrays, region size 1 MB:
end of minor GC / G1 Humongous Allocation (several times)
3. System.gc():
end of major GC / System.gc() (once)
- The small arrays caused ordinary young collections, "G1 Evacuation Pause": eden was full.
- The 600 KB arrays caused collections with the cause "G1 Humongous Allocation". In G1, an object of at least half a region is humongous: it is allocated directly in the old generation, in one or more whole regions of its own. Each such array used a full 1 MB region, wasting the remaining 424 KB, and allocating many of them triggers collections that would not otherwise be needed. Large buffers that are created and dropped often are worth pooling, or the region size can be raised with
.-XX:G1HeapRegionSize caused a full ("major") collection. Libraries that call it can stall an application;System.gc() turns such calls into no-ops.-XX:+DisableExplicitGC- For day-to-day diagnosis,
prints one line per collection with the same cause, the heap before and after, and the pause time;-Xlog:gcthe GC deep dive reads those logs in detail.
One workload, four collectors
The same program, which keeps a 100 MB working set and allocates about 1.8 GB of short-lived arrays while replacing some of its old objects, runs in four child JVMs with a 512 MB heap. Each prints its wall time and what every collector bean recorded. This is a single rough run on a 2-CPU machine, not a benchmark; the point is the shape of the numbers, not the exact values.
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class CollectorRace {
// The workload: keep a 100 MB working set while churning through short-lived objects
public static class Workload {
static volatile byte[] sink; // makes the garbage escape
public static void main(String[] args) {
List<byte[]> live = new ArrayList<>();
for (int i = 0; i < 100; i++) {
live.add(new byte[1 << 20]);
}
long t0 = System.nanoTime();
long sum = 0;
for (int i = 0; i < 20000000; i++) {
byte[] tmp = new byte[64 + (i & 63)]; // short-lived garbage
sink = tmp;
sum += tmp.length;
if ((i & 0xFFFF) == 0) {
live.set((i >> 16) % 100, new byte[1 << 20]); // some old objects change
}
}
long ms = (System.nanoTime() - t0) / 1000000;
StringBuilder beans = new StringBuilder();
for (var gc : ManagementFactory.getGarbageCollectorMXBeans()) {
beans.append(String.format(" [%s: %d, %d ms]", gc.getName(),
gc.getCollectionCount(), gc.getCollectionTime()));
}
System.out.printf("%,5d ms, %,d MB allocated%s%n", ms, sum >> 20, beans);
}
}
public static void main(String[] args) throws IOException, InterruptedException {
String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
String cp = System.getProperty("java.class.path");
for (String gc : new String[] {"-XX:+UseSerialGC", "-XX:+UseParallelGC",
"-XX:+UseG1GC", "-XX:+UseZGC"}) {
List<String> cmd = new ArrayList<>(List.of(java, gc, "-Xmx512m", "-cp", cp,
"CollectorRace$Workload"));
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
p.getOutputStream().close();
String out = new String(p.getInputStream().readAllBytes()).trim();
p.waitFor();
System.out.printf("%-19s %s%n", gc.substring(8), out.lines()
.filter(l -> !l.startsWith("Picked up")).findFirst().orElse(out));
}
}
}
Output (2-CPU Linux machine, JDK 21, one run per collector):
SerialGC 610 ms, 1,821 MB allocated [Copy: 42, 208 ms] [MarkSweepCompact: 5, 79 ms]
ParallelGC 572 ms, 1,821 MB allocated [PS MarkSweep: 1, 27 ms] [PS Scavenge: 18, 158 ms]
G1GC 550 ms, 1,821 MB allocated [G1 Young Generation: 107, 57 ms] [G1 Concurrent GC: 132, 23 ms] [G1 Old Generation: 0, 0 ms]
ZGC 533 ms, 1,821 MB allocated [ZGC Cycles: 9, 75 ms] [ZGC Pauses: 27, 0 ms]
- Serial and Parallel do all their work in stop-the-world pauses, so their reported collection time is time the application stood still. Parallel needed fewer collections than Serial, because it sizes its young generation for throughput.
- G1 ran by far the most collections, many small young pauses chosen to stay under its pause-time target, and its "Concurrent GC" bean counts the phases of its background marking cycle. G1 does not promise less total GC time; on a small heap and 2 busy CPUs its total can even be higher. What it bounds is the length of each individual pause, which is what users of a service notice.
- ZGC's "Pauses" bean reported dozens of pauses that together rounded to 0 ms: its pauses are well under a millisecond. Its "Cycles" time is concurrent work done on other threads, which competes with the application for CPU instead of stopping it.
- The wall times changed noticeably from run to run on this shared machine, so do not read a ranking into them. They matter with large heaps and many threads, where a Serial or Parallel full collection can pause for seconds.
OutOfMemoryError and its relatives
An OutOfMemoryError
import java.util.ArrayList;
import java.util.List;
public class OutOfMemory {
public static void main(String[] args) {
List<long[]> leak = new ArrayList<>();
try {
while (true) {
leak.add(new long[1000000]); // 8 MB each, never released
}
} catch (OutOfMemoryError e) {
int held = leak.size();
leak.clear(); // free memory so we can print
System.out.println("OutOfMemoryError: " + e.getMessage());
System.out.println("thrown after " + held + " arrays, about " + held * 8 + " MB");
}
// Unbounded recursion fills the thread's stack, not the heap
try {
recurse(0);
} catch (StackOverflowError e) {
System.out.println("StackOverflowError: the call stack is separate from the heap");
}
}
static int recurse(int depth) {
return recurse(depth + 1) + 1;
}
}
Output (run with -Xmx64m
OutOfMemoryError: Java heap space
thrown after 7 arrays, about 56 MB
StackOverflowError: the call stack is separate from the heap
- The error came after 7 arrays, about 56 MB: the rest of the 64 MB heap was taken by the JVM's own objects and by the fact that an 8 MB array needs one contiguous block. Catching the error and dropping the list made enough memory free again to continue, which is useful only in a demo; in real code, after an
the application's state is suspect.OutOfMemoryError - Recursion without end produced
instead, because the call stack is a separate, per-thread area.StackOverflowError
| Message | Meaning | First step |
|---|---|---|
| Java heap space | Live objects exceed -Xmx | Heap dump with -XX:+HeapDumpOnOutOfMemoryError |
| GC overhead limit exceeded | Parallel GC spent over 98% of time collecting and freed under 2% | Same as above; the heap is nearly full of live data |
| Metaspace | Too much class metadata | Look for class loader leaks; set -XX:MaxMetaspaceSize |
| Cannot reserve ... bytes of direct buffer memory | Direct buffers exceed MaxDirectMemorySize | Reuse direct buffers |
| unable to create native thread | The OS refused another thread | Count threads; use pools or virtual threads |
| Requested array size exceeds VM limit | An array longer than the JVM allows, near Integer.MAX_VALUE | Fix the size calculation |
Choosing a collector and the first flags to set
| Situation | Use |
|---|---|
| Most services and applications | G1 (the default), with -Xmx |
| Large heaps or strict latency goals | ZGC; on Java 21 add -XX:+ZGenerational |
| Batch processing where only total time counts | Parallel GC |
| Tiny containers with one CPU, short command-line tools | Serial GC |
| A pause-time goal for G1 | -XX:MaxGCPauseMillis |
| Seeing what the collector does | -Xlog:gc*:file=gc.log |
| Diagnosing memory errors | -XX:+HeapDumpOnOutOfMemoryError |
Tune only after measuring. See