Garbage collection basics
Nothing is freed because you asked. Objects go when no living code can reach them any more.
Open this lesson in the learning hubKey points
- You never free memory yourself. The collector finds objects that no running code can reach and reclaims the space.
- Unreachable is the only rule. Assigning
nullhelps only if that was genuinely the last way in. System.gc()is a suggestion, not a command. Production code should almost never call it.- A
WeakReferencedoes not keep its target alive, which makes it the honest way to watch a collection happen. - Collection is not free. It costs CPU, and most collectors still stop your threads briefly while they work.
Example
import java.lang.ref.WeakReference;
public class Main {
public static void main(String[] args) throws InterruptedException {
Object strong = new Object();
WeakReference<Object> watch = new WeakReference<>(strong);
System.out.println("while a variable points at it -> alive? " + (watch.get() != null));
strong = null; // the last strong reference is gone
for (int i = 0; i < 5 && watch.get() != null; i++) {
System.gc(); // a hint, not a command
Thread.sleep(50);
}
System.out.println("after the reference is dropped -> alive? " + (watch.get() != null));
System.out.println(watch.get() == null
? "collected: nothing in the program could reach it any more"
: "not collected yet - System.gc() really is only a hint");
}
}
Reachable means alive. Everything else is fair game.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the JVM course, and every lesson in it is listed on the JVM contents page.