Part 13 / Topic 2 of 8
The heap in practice: allocation, garbage collection, and references
Garbage collection (GC) is the JVM automatically freeing heap objects that nothing can reach any more, so you never call free() yourself. "Nothing can reach" means: starting from a set of roots (local variables on every thread's stack, static fields, …), no chain of references leads to the object.
Think of the kitchen shelf again: a jar nobody has written down on any recipe card, and that no other jar on the shelf points to, might as well not be there — eventually someone clears it to make room.
Short-lived objects are the common case, and the default collector (G1, on most machines) is tuned for exactly that: most objects die young, in a fast, frequent young-generation collection; a smaller number of long-lived objects get promoted and collected less often. -Xlog:gc prints a line every time a collection actually runs:
for (int round = 0; round < 2_000; round++) {
byte[] churn = new byte[64 * 1024]; // garbage the instant the next round starts
...
}
$ javac AllocationChurn.java
$ java -Xlog:gc AllocationChurn
[0.005s][info][gc] Using G1
[0.017s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 32M->1M(776M) 0.829ms
rounds done, bytes touched: 2000
2,000 rounds of a fresh 64 KiB array, immediately dropped, is enough garbage to trigger one real young-generation pause (32M->1M(776M): 32 MiB in use before the pause, 1 MiB after, inside a region currently sized at 776 MiB) — the pause itself cost well under a millisecond here. Running the plain program with no flag produces no GC output at all because -Xlog:gc is what turns logging on, not something the program does.
Strong and weak references
Every reference you've written so far — a field, a local variable, a list element — is a strong reference: as long as one exists, the object cannot be collected, full stop. java.lang.ref.WeakReference<T> is different: it lets you hold onto an object without that hold, by itself, keeping it alive.
Session asha = new Session("asha");
WeakReference<Session> weak = new WeakReference<>(asha);
asha = null; // the only strong reference is gone
System.gc(); // a request, not a guarantee
$ javac StrongAndWeakReferences.java
$ java StrongAndWeakReferences
== 1. A strong reference keeps the object reachable ==
weak.get() while asha still holds it: Session(asha)
== 2. Drop the only strong reference, ask the GC to run, then check again ==
weak.get() after dropping the strong reference and System.gc(): null
(a WeakReference never keeps an object alive by itself; once nothing else does, it clears)
== 3. WeakHashMap: a cache whose entries disappear once the key is otherwise unused ==
cache size while ravi is referenced: 1
cache size after dropping the only strong reference to the key: 0
A plain HashMap would have kept that entry (and the Session) alive forever.
weak.get() returns the object while it's still reachable some other way, and null once it isn't — the garbage collector cleared the weak reference itself as part of collecting the Session. WeakHashMap uses exactly this: its keys are held weakly, so an entry disappears on its own once nothing outside the map still references that key — useful for a cache that should never be the reason an object stays alive.
⚠️
System.gc()is a request, not a command. The JVM is free to ignore it. It's used here only to make a demo's timing predictable; real code should never depend on a garbage collection happening at a particular moment.
Full program: examples/AllocationChurn.java, examples/StrongAndWeakReferences.java.
Done here? The practice set for Part 13 — including the solutions — is on the part page.