Garbage Collection
- Garbage collection (GC) is how Java frees heap memory automatically
- You create objects with
new, but you never delete them. The garbage collector finds objects the program can no longer use and reclaims their memory - It prevents bugs like freeing memory twice or using memory after it was freed, but it does not prevent every memory leak
- Basics of the heap and the stack are in Stack and Heap Memory
Reachability
The GC doesn’t ask “is this object still needed?”. It asks “can the program still reach it?”.
- GC roots are references the JVM knows are live. The main ones:
- Local variables and parameters in the stack frames of running threads
- Static fields of loaded classes
- Running threads themselves
- References held by native (JNI) code
- An object is reachable if there is a chain of references from a GC root to it
- An object that isn’t reachable is eligible for garbage collection
An object usually becomes unreachable when:
- The only reference to it is set to
null - The only reference to it is reassigned to another object
- The method holding the only reference returns, so its stack frame is gone
- It is only part of a cycle: objects pointing to each other, with nothing reachable pointing to any of them
Box x = new Box("X");
Box y = new Box("Y");
x.other = y;
y.other = x;
x = null;
y = null; // X and Y still point to each other, but both are now eligible For each case, see this code (Reachability.java, below).
// Shows the ways an object stops being reachable and becomes eligible for garbage collection
class Box {
String label;
Box other;
Box(String label) {
this.label = label;
}
}
public class Reachability {
static Box saved; // a static field is a GC root
public static void main(String[] args) {
// 1. Setting the only reference to null
Box a = new Box("A");
a = null; // "A" is now unreachable -> eligible
// 2. Reassigning the only reference
Box b = new Box("B1");
b = new Box("B2"); // "B1" is now unreachable -> eligible
// 3. The method holding the only reference returns
makeTemporary(); // "Temp" was only referenced from that method's frame
// 4. A cycle with nothing outside pointing to it
Box x = new Box("X");
Box y = new Box("Y");
x.other = y;
y.other = x;
x = null;
y = null; // X and Y still point to each other, but nothing reachable points to them -> both eligible
// 5. Still reachable: saved in a static field
keepForever();
System.out.println(saved.label); // Kept
System.out.println(b.label); // B2
}
static void makeTemporary() {
Box temp = new Box("Temp");
System.out.println(temp.label); // Temp
}
static void keepForever() {
Box kept = new Box("Kept");
saved = kept; // escapes into a static field, so it outlives this method
}
}Eligible doesn’t mean collected. When (or whether) the GC runs is up to the JVM. A program that exits early may never collect some of its garbage.
Java’s GC does not use reference counting, so cycles are not a problem.
How a Collector Works
HotSpot’s collectors are tracing collectors. They all build on the same basic idea:
- Mark: start from the GC roots and mark every object that can be reached
- Reclaim: everything not marked is garbage. Depending on the collector, its memory is either swept (recorded as free) or the live objects are copied out so the whole area can be reused
- Compact: move live objects together so free memory is one big block, not many small gaps
- While some of this work runs, the collector may stop all application threads. This is a stop-the-world pause
- Collectors differ mainly in how much work they do during pauses and how much they do concurrently, while your program keeps running
Generations
- Most objects die young: temporary strings, iterators, objects used for one calculation
- So most HotSpot collectors split the heap into generations:
- Young generation: where new objects are created. Collected often, and quickly, because most of it is garbage
- Old generation: objects that survived several young collections are promoted here. Collected less often
- In HotSpot, the young generation is further split into Eden (where objects are created) and two survivor spaces (where live objects are copied between collections)
- How many collections an object survives before promotion is limited by
-XX:MaxTenuringThreshold(15 by default in HotSpot)
G1 divides the heap into many equal-size regions, and each region plays the role of Eden, survivor or old. The idea of generations is the same.
Collectors in HotSpot
| Collector | Flag | Good for |
|---|---|---|
| Serial | -XX:+UseSerialGC | Small heaps, single-CPU machines, small tools. One GC thread |
| Parallel | -XX:+UseParallelGC | Batch jobs where total throughput matters more than pause length |
| G1 (default) | -XX:+UseG1GC | General use: balances throughput and pause times |
| ZGC | -XX:+UseZGC | Very short pauses (typically under a millisecond), even with huge heaps |
| Shenandoah | -XX:+UseShenandoahGC | Very short pauses, similar goals to ZGC |
- G1 has been the default since Java 9. On a small machine (fewer than 2 CPUs or less than about 1.8 GB of memory), the JVM picks Serial instead
- Parallel was the default up to Java 8
- ZGC is production-ready since Java 15 and generational since Java 21 (the only mode since Java 24)
- Shenandoah is production-ready since Java 15, but it is not included in Oracle JDK builds. It’s in builds such as Eclipse Temurin and Red Hat’s
- The old CMS collector was removed in Java 14
For learning and most programs, keep the default (G1). Change collector only after measuring a real problem.
Watching the GC
Run a program with -Xlog:gc (since Java 9) to print a line for every collection. For example, with this code (GarbageMaker.java, below):
// Creates lots of short-lived objects so you can watch the garbage collector with -Xlog:gc
public class GarbageMaker {
public static void main(String[] args) {
long total = 0;
for (int i = 0; i < 2_000; i++) {
byte[] temp = new byte[100_000]; // becomes garbage at the end of each iteration
total += temp.length;
}
System.out.println("Allocated " + total / 1_000_000 + " MB in total"); // Allocated 200 MB in total
}
}The interesting part is the GC log from `java -Xlog:gc`, which needs a JVM flag. Run it on your computer with java GarbageMaker.java.
java -Xmx64m -Xlog:gc GarbageMaker [0.004s][info][gc] Using G1
[0.017s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 35M->1M(64M) 0.283ms
[0.017s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 30M->1M(64M) 0.152ms
...
Allocated 200 MB in total Pause Young: a young-generation collection35M->1M(64M): heap use went from 35 MB to 1 MB, out of 64 MB in total. Nearly everything was garbage0.283ms: how long the pause took
The output above is from one run on JDK 25. Timings, sizes and the number of collections change between runs, machines and JDK versions.
Other useful tools that come with the JDK:
jcmd <pid> GC.heap_info: shows heap usage of a running program (find the pid withjcmdalone)jstat -gc <pid> 1000: prints GC statistics every second- VisualVM (separate download): graphs heap usage and GC activity live
Common heap and GC flags:
| Flag | Meaning |
|---|---|
-Xms512m | Starting heap size |
-Xmx2g | Maximum heap size |
-XX:+UseG1GC (etc.) | Choose the collector |
-XX:MaxGCPauseMillis=100 | Pause-time goal for G1 (a target, not a promise; default 200) |
-Xlog:gc | Log each collection |
System.gc()
System.gc()only suggests that the JVM run a collection. The JVM may ignore it (for example with-XX:+DisableExplicitGC)- In normal code you don’t need it. The JVM decides better when to collect
- It’s fine in small experiments like the ones in this note, but never rely on it for correctness
Reference Types
Normal variables are strong references. The java.lang.ref package has weaker kinds, which let the GC collect an object even though you still have a reference object pointing to it:
| Type | Cleared when | get() returns | Typical use |
|---|---|---|---|
| Strong (normal) | Never, while reachable | (no get(), it’s a variable) | Everyday code |
SoftReference | The GC may clear it when memory is low | The object, or null | Memory-sensitive caches |
WeakReference | At the next GC that finds it only weakly reachable | The object, or null | Data attached to objects you don’t own |
PhantomReference | Enqueued when the object is about to be reclaimed | Always null | Cleanup after collection (Cleaner) |
WeakReference<byte[]> weak = new WeakReference<>(weakData);
System.out.println(weak.get() != null); // true (weakData still holds it strongly)
weakData = null;
System.gc();
System.out.println(weak.get()); // typically null now, but not guaranteed For all four, see this code (ReferenceTypes.java, below).
// Shows strong, soft, weak and phantom references and what get() returns for each
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
public class ReferenceTypes {
public static void main(String[] args) {
// Separate objects: if one object had both a soft and a weak reference,
// it would count as softly reachable and the weak reference would not be cleared
byte[] softData = new byte[1024];
byte[] weakData = new byte[1024];
byte[] phantomData = new byte[1024];
SoftReference<byte[]> soft = new SoftReference<>(softData);
WeakReference<byte[]> weak = new WeakReference<>(weakData);
PhantomReference<byte[]> phantom = new PhantomReference<>(phantomData, new ReferenceQueue<>());
// While a strong reference exists, soft and weak references are guaranteed to work
System.out.println(soft.get() != null); // true
System.out.println(weak.get() != null); // true
System.out.println(phantom.get()); // null (always, by design)
// Drop the strong references
softData = null;
weakData = null;
phantomData = null;
System.gc(); // only a request
// NOT guaranteed: the results below can differ between JVMs and runs.
// Typically the weak one is cleared and the soft one is kept while memory is plentiful.
System.out.println("weak after gc: " + (weak.get() == null ? "cleared" : "still there")); // typical: cleared
System.out.println("soft after gc: " + (soft.get() == null ? "cleared" : "still there")); // typical: still there
}
}The browser's garbage collector doesn't clear weak references the way a real JVM does, so the output would be misleading. Run it on your computer with java ReferenceTypes.java.
An object is only as collectable as its strongest path. If one object has both a soft and a weak reference, it is softly reachable, so the weak reference is not cleared either.
The JVM guarantees that all softly reachable objects are cleared before it throws OutOfMemoryError.
WeakHashMap
- A
Mapwhose keys are held by weak references - When a key is no longer strongly reachable anywhere else, its entry disappears from the map after a GC
- Useful for attaching extra data to objects without keeping those objects alive
- Only the keys are weak. If a value refers to its own key, the entry is never removed
Memory Leaks in Java
- In Java, a memory leak means objects stay reachable even though the program will never use them again
- The GC can’t help, because from its point of view they are still in use
- Over time the heap fills up and the program ends with
OutOfMemoryError
Common causes:
- Collections that only grow, especially in
staticfields: caches with no limit, lists you only add to - Listeners and callbacks that are registered but never unregistered
ThreadLocalvalues in thread pools: pool threads live for a long time, so their values do too unless you callremove()- Inner class instances (non-static) kept alive somewhere: each one can hold a hidden reference to its outer object, keeping it alive too. (Since Java 18, javac leaves that reference out if the inner class never uses the outer object.) Make the nested class
staticif it doesn’t need the outer object - Wrong
equals/hashCodeon keys of aHashMap/HashSet: you add “the same” key again and again, and old entries can never be found or removed
for (int i = 0; i < 1000; i++) {
Screen s = new Screen();
s.open(); // registers a listener in a static list
} // 's' is gone, but each listener is still in the list
System.out.println(EventBus.listeners.size()); // 1000 For the leak and its fix (unregister in close()), see this code (ListenerLeak.java, below).
// Shows a classic Java memory leak: objects stay reachable from a static list after you're done with them
import java.util.ArrayList;
import java.util.List;
class EventBus {
static final List<Runnable> listeners = new ArrayList<>(); // static = lives as long as the class
static void register(Runnable listener) {
listeners.add(listener);
}
static void unregister(Runnable listener) {
listeners.remove(listener);
}
}
class Screen {
byte[] image = new byte[10_000]; // pretend each screen holds a large image
Runnable listener = () -> System.out.println("refresh");
void open() {
EventBus.register(listener);
}
void close() {
EventBus.unregister(listener);
}
}
public class ListenerLeak {
public static void main(String[] args) {
// Leaky: screens are opened but never closed
for (int i = 0; i < 1000; i++) {
Screen s = new Screen();
s.open();
} // every local variable 's' is gone, but each listener (a lambda) is still in the static list
System.out.println("Listeners after leaky loop: " + EventBus.listeners.size()); // 1000
EventBus.listeners.clear();
// Fixed: unregister when done, so nothing keeps the screens reachable
for (int i = 0; i < 1000; i++) {
Screen s = new Screen();
s.open();
s.close();
}
System.out.println("Listeners after fixed loop: " + EventBus.listeners.size()); // 0
}
}Too heavy to run in the browser. Run it on your computer with java ListenerLeak.java.
Cleaning Up Resources
- The GC frees memory, not other resources like files, sockets or database connections
- These must be closed explicitly, at a known point. Use try-with-resources (since Java 7) with any
AutoCloseable:
try (Connection c = new Connection("db")) {
c.send("query");
} // close() runs here, even if an exception is thrown For the full example, see this code (CleanupDemo.java, below).
// Shows that try-with-resources closes a resource at a known point, unlike the garbage collector
class Connection implements AutoCloseable {
private final String name;
Connection(String name) {
this.name = name;
System.out.println("open " + name);
}
void send(String msg) {
System.out.println(name + " sends " + msg);
}
@Override
public void close() {
System.out.println("close " + name);
}
}
public class CleanupDemo {
public static void main(String[] args) {
try (Connection c = new Connection("db")) {
c.send("query");
} // close() runs here, even if an exception is thrown
System.out.println("after try");
}
}finalize(): a method the GC might call before collecting an object. It is unreliable (it may run late or never) and slow. Deprecated in Java 9 and marked for removal in Java 18. Don’t use itjava.lang.ref.Cleaner(since Java 9): registers an action to run after an object becomes phantom reachable. Use it only as a safety net for when someone forgets to callclose(), never as the main way to clean up
Common Mistakes
- Thinking an object is collected as soon as it is eligible. It may happen much later, or never
- Calling
System.gc()to “fix” memory problems. It’s only a hint and usually makes things slower - Believing Java can’t leak memory. Anything still reachable stays, even if you’ll never use it again
- Relying on the GC (or
finalize()) to close files and connections. Use try-with-resources - Expecting a
WeakReferenceto be cleared while something else (even aSoftReference) still reaches the object - Changing the collector or tuning flags without measuring first. Defaults are good for most programs