The labs on this site need JavaScript to run. The same content is written out below.
Learn › Java › JVM
GC and memory leaks
Who reclaims discarded objects, and when?
Why it exists — In a language where you handle memory directly, such as C, the developer must release memory after use, and mistakes such as forgetting to release it or using memory that has already been released break the program. Java's GC lets the JVM find and clear objects that cannot be reached from anywhere, so that developers do not have to write code that returns memory.
Where it's used today — A Java program runs GC whenever the JVM needs it, without your turning it on. Developers look into GC when they search for the cause of an occasional pause in responses, when they decide the heap size and the kind of GC such as G1, and when an OutOfMemoryError occurs and they use the GC log and a heap dump to find objects that keep staying in memory.
Garbage collection (GC) is the JVM automatically reclaiming the memory of objects that are no longer used. New objects are created in eden, and when eden fills up, a minor GC picks out only the live objects and moves them. Objects that survive several times are promoted to the old generation, and when the old generation does not have enough room for more promotions, a full GC runs and cleans up the whole heap. A memory leak is the buildup of objects that are no longer needed but cannot be collected because something still refers to them, and this lab also shows what happens to the heap when there is a leak.
Checked against real execution · All 324 combinations checked against the GC log of the Serial GC on JDK 21
Concepts in this lab
- Garbage collection (GC)
- This JVM feature finds objects that the program no longer uses and reclaims their memory automatically. Developers do not have to free memory themselves, which prevents errors caused by mistakes in freeing it. In return, the application may pause briefly during a collection, and objects that are still referenced cannot be reclaimed.
- Reachability and GC roots
- Why it exists — A method that counts references and deletes an object when the count reaches 0 leaves objects that form a cycle by referring to each other, because their counts never reach 0 even though no one uses them. The reachability criterion looks only at whether an object can be reached from a GC root, so it reclaims such a cycle as a whole.
- Where it's used today — When looking for a memory leak, you use a heap dump analysis tool such as Eclipse MAT to follow the reference path from an object to a GC root and see what is holding on to that object.
- The GC decides whether an object is still in use by asking "is it reachable?". An object that can be reached by following references from starting points that are always alive (GC roots), such as the local variables of running threads and static variables, is treated as live, and an object that cannot be reached is treated as a candidate for reclamation.
- Young generation and old generation
- This structure divides the heap based on the observation that most objects become useless soon after they are created. New objects are created in the young generation (in eden), and objects that survive several collections of the young generation are moved to the old generation. Collecting only the young generation often, where short-lived objects gather, reclaims a lot of memory at low cost.
- Minor GC and full GC
- A minor GC (young GC) collects only the young generation; it happens often but usually finishes quickly. A full GC collects the whole heap; it takes a long time and also pauses the application for longer. If full GCs happen often, or memory use does not go down even after a full GC, suspect a memory leak or a heap that is too small.
- Stop-the-world (STW)
- This means pausing all threads of the application so that garbage collection can be done safely. Request handling stops during this time, so it shows up as response delays. Recent collectors (G1, ZGC) are designed with the goal of keeping these pauses short.
- Memory leak
- This is a state in which objects that are no longer needed are still referenced from somewhere, so the garbage collector cannot reclaim them. Memory use grows over time and eventually leads to an OutOfMemoryError. Typical causes are data that keeps piling up in a static collection, a cache with no expiration, and ThreadLocal values that are not cleaned up in a thread pool.
- StackOverflowError and OutOfMemoryError
- A StackOverflowError occurs when method calls go so deep that they exceed the thread's stack space, and the usual cause is recursion with a wrong termination condition. An OutOfMemoryError occurs when memory such as the heap runs short and no more objects can be allocated, and common causes are a memory leak or loading too much data at once.
Try these
- Default settings — Most objects are discarded quickly. Minor GCs alone keep the program going.
- With many long-lived objects — More objects are promoted to the old generation, and full GCs start to run.
- Creating objects faster — Eden fills up sooner, so minor GCs become more frequent.
- With a larger heap — The number of GCs goes down.
- Memory leak — Full GCs run again and again, but the free room only shrinks, and the run ends with an OutOfMemoryError.
- A leak with only a larger heap — This only delays the point of failure.
Running with the default settings
- Tick 1: 5 objects are created. Eden: 5/22 slots in use.
- Tick 2: 5 objects are created. Eden: 10/22 slots in use.
- Tick 3: 5 objects are created. Eden: 15/22 slots in use.
- Tick 4: 5 objects are created. Eden: 20/22 slots in use.
- Tick 5: Eden is full. A minor GC examines only the young generation (objects: 22). It discards the objects that are not referenced (19) and moves the live objects (3). Moved to the survivor space: 3. Promoted to the old generation: 0. Eden is now empty. All threads of the application are paused during this time.
- Tick 5: 5 objects are created. Eden: 3/22 slots in use.
- Tick 6: 5 objects are created. Eden: 8/22 slots in use.
- Tick 7: 5 objects are created. Eden: 13/22 slots in use.
- Tick 8: 5 objects are created. Eden: 18/22 slots in use.
- Tick 9: Eden is full. A minor GC examines only the young generation (objects: 25). It discards the objects that are not referenced (20) and moves the live objects (5). Moved to the survivor space: 2. Promoted to the old generation: 3 (survived once more in the survivor space: 3). Eden is now empty. All threads of the application are paused during this time.
- Tick 9: 5 objects are created. Eden: 1/22 slots in use.
- Tick 10: 5 objects are created. Eden: 6/22 slots in use.
- Tick 11: 5 objects are created. Eden: 11/22 slots in use.
- Tick 12: 5 objects are created. Eden: 16/22 slots in use.
- Tick 13: 5 objects are created. Eden: 21/22 slots in use.
- Tick 14: Eden is full. A minor GC examines only the young generation (objects: 24). It discards the objects that are not referenced (20) and moves the live objects (4). Moved to the survivor space: 2. Promoted to the old generation: 2 (survived once more in the survivor space: 2). Eden is now empty. All threads of the application are paused during this time.
- Tick 14: 5 objects are created. Eden: 4/22 slots in use.
- Tick 15: 5 objects are created. Eden: 9/22 slots in use.
- Tick 16: 5 objects are created. Eden: 14/22 slots in use.
- Tick 17: 5 objects are created. Eden: 19/22 slots in use.
- Tick 18: Eden is full. A minor GC examines only the young generation (objects: 24). It discards the objects that are not referenced (20) and moves the live objects (4). Moved to the survivor space: 2. Promoted to the old generation: 2 (survived once more in the survivor space: 2). Eden is now empty. All threads of the application are paused during this time.
- Tick 18: 5 objects are created. Eden: 2/22 slots in use.
- Tick 19: 5 objects are created. Eden: 7/22 slots in use.
- Tick 20: 5 objects are created. Eden: 12/22 slots in use.
- Tick 21: 5 objects are created. Eden: 17/22 slots in use.
- Tick 22: 5 objects are created. Eden: 22/22 slots in use.
- Tick 23: Eden is full. A minor GC examines only the young generation (objects: 24). It discards the objects that are not referenced (20) and moves the live objects (4). Moved to the survivor space: 2. Promoted to the old generation: 2 (survived once more in the survivor space: 2). Eden is now empty. All threads of the application are paused during this time.
- Tick 23: 5 objects are created. Eden: 5/22 slots in use.
- Tick 24: 5 objects are created. Eden: 10/22 slots in use.
- Tick 25: 5 objects are created. Eden: 15/22 slots in use.
- Tick 26: 5 objects are created. Eden: 20/22 slots in use.
- Tick 27: Eden is full. A minor GC examines only the young generation (objects: 24). It discards the objects that are not referenced (19) and moves the live objects (5). Moved to the survivor space: 3. Promoted to the old generation: 2 (survived once more in the survivor space: 2). Eden is now empty. All threads of the application are paused during this time.
- Tick 27: 5 objects are created. Eden: 3/22 slots in use.
- Tick 28: 5 objects are created. Eden: 8/22 slots in use.
- Tick 29: 5 objects are created. Eden: 13/22 slots in use.
- Tick 30: 5 objects are created. Eden: 18/22 slots in use.
- Tick 31: Eden is full. A minor GC examines only the young generation (objects: 25). It discards the objects that are not referenced (20) and moves the live objects (5). Moved to the survivor space: 2. Promoted to the old generation: 3 (survived once more in the survivor space: 3). Eden is now empty. All threads of the application are paused during this time.
- Tick 31: 5 objects are created. Eden: 1/22 slots in use.
- Tick 32: 5 objects are created. Eden: 6/22 slots in use.
- Tick 33: 5 objects are created. Eden: 11/22 slots in use.
- Tick 34: 5 objects are created. Eden: 16/22 slots in use.
- Tick 35: 5 objects are created. Eden: 21/22 slots in use.
- Tick 36: Eden is full. A minor GC examines only the young generation (objects: 24). It discards the objects that are not referenced (20) and moves the live objects (4). Moved to the survivor space: 2. Promoted to the old generation: 2 (survived once more in the survivor space: 2). Eden is now empty. All threads of the application are paused during this time.
- Tick 36: 5 objects are created. Eden: 4/22 slots in use.
- Tick 37: 5 objects are created. Eden: 9/22 slots in use.
- Tick 38: 5 objects are created. Eden: 14/22 slots in use.
- Tick 39: 5 objects are created. Eden: 19/22 slots in use.
- Tick 40: Eden is full. A minor GC examines only the young generation (objects: 24). It discards the objects that are not referenced (20) and moves the live objects (4). Moved to the survivor space: 2. Promoted to the old generation: 2 (survived once more in the survivor space: 2). Eden is now empty. All threads of the application are paused during this time.
- Tick 40: 5 objects are created. Eden: 2/22 slots in use.
Result of this run
- Most objects were discarded quickly, so minor GCs alone were enough. Dividing the heap into generations is efficient when the assumption that "most objects die young" holds.
Code
// Heap: eden 22 slots, survivor 4 slots, old 44 slots (one slot = 4MB)
// EventLoop and Event are names made up for this example (imports omitted, only the relevant parts kept).
class EventLoop {
static final int CELL = 4 * 1024 * 1024 - 16; // array length that makes one object fill one heap slot (4MB)
static List<Event> held = new ArrayList<>(1000); // list that holds objects while they are in use
void run() {
long nextId = 0;
for (long tick = 1; tick <= 40; tick++) { // one pass = one tick
long now = tick;
held.removeIf(x -> x.until() <= now); // drops references whose time of use is over
for (int i = 0; i < 5; i++) create(nextId++, now);
}
}
void create(long id, long now) {
byte[] body = new byte[CELL]; // created in eden (one slot)
long kind = id % 10; // cycles through 0 to 9
if (kind < 1) held.add(new Event(id, now + 10, body)); // 10%: referenced for 10 ticks
} // anything not added to the list is discarded here
}
record Event(long id, long until, byte[] body) {}
Assumptions of this model
This model expresses in slots what the Serial GC of JDK 21 (Temurin 21.0.12) does, and one object fills one slot (4MB). The program on screen was run on a real JVM in all 324 combinations that you can choose on screen and checked against the GC log (-Xlog:gc*). For every combination, the tick at which each GC ran and its kind, the number of slots in use in eden, the survivor space, and the old generation before and after it, the old generation usage at the end, and whether an OutOfMemoryError occurred were all the same (324 / 324 matched, 3,750 GCs). The options were -XX:+UseSerialGC, a fixed heap size (-Xms, -Xmx, -Xmn), -XX:SurvivorRatio=5, -XX:MaxTenuringThreshold=1, -XX:-UseTLAB, and -XX:MarkSweepDeadRatio=0. MaxTenuringThreshold=1 makes objects get promoted at their second minor GC. The default maximum is 15, and the JVM adjusts it to the situation. Each area was given about half a slot of extra room, and before the measurement the same code was run once with small objects and the heap was cleaned up with System.gc() (the GCs of this preparation step are not counted). The count of minor GCs includes only the ones that ran to completion. The ones that the JVM did not run because it expected the old generation to lack room, and the ones that it could not finish because promotion failed, also appear in the log as Pause Young, but they are left out of the count. The 41 combinations that have a leak but lasted 40 ticks were run up to 400 ticks, and all of them ended with an OutOfMemoryError. Pause times are not shown on screen. With few, large objects as in this program, the averages of Pause Young and Pause Full were similar (14.2ms and 15.0ms on this computer), and when a program that creates many 10KB objects was run with the Serial GC (64MB heap), the average was 1.3ms for Pause Young and 7.0ms for Pause Full. These times differ on every run. Run with no options on this computer, JDK 21 selects G1. G1 and ZGC work differently, for example by dividing the heap into smaller parts and working concurrently with the application, so the counts and the order in this lab hold only for the Serial GC. The principle is the same: the area for new objects and the area for old objects are handled separately, and objects that are still referenced cannot be reclaimed.
Previous lab: Stack and heap · Next lab: JIT warmup