What garbage collection does
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Your program creates millions of objects, such as orders and students, with new, and never frees any of them. Memory should run out quickly, but it does not. Who is cleaning up?
Automatic memory management: no free() in Java
Garbage collection is the JVM automatically finding objects that can no longer be reached and freeing their memory.
Automatic memory management means the JVM, not your code, decides when an object's memory can be reused. The part of the JVM that does this is the garbage collector.
Example 1 · A million objects and not one free()
class Ticket { String passenger; int fare;
Ticket(String passenger, int fare) { this.passenger = passenger; this.fare = fare; }}
public class NoFreeDemo { public static void main(String[] args) { long totalFare = 0; for (int i = 1; i <= 1_000_000; i++) { Ticket t = new Ticket("P" + i, 150 + i % 50); // a new object every time totalFare += t.fare; } // t's old object is garbage now System.out.println("Tickets booked: 1000000"); System.out.println("Total fare: Rs " + totalFare); }}Tickets booked: 1000000 Total fare: Rs 174500000
What this code does
- Each loop step creates a
Ticketand aString. In the next steptpoints to a new ticket, so the old one is garbage. Nothing in the code frees it. - Run it as
java -Xmx16m -Xlog:gc NoFreeDemoand it still finishes in a 16 MB heap: the log shows collections reclaiming dead tickets while the loop runs.
In C you ask for memory with malloc and must give it back with free. Forget free and memory runs out slowly. Call free too early and another part of the program reads memory that now belongs to something else. Java has new but no free or delete, so those two bugs cannot happen. The collector runs on its own when the heap (the memory area for objects) fills up. Your code just keeps creating objects.
What counts as garbage
An object is garbage when no running part of your program can reach it any more: no live local variable, no static field and no other reachable object holds a reference to it. Such an object is called eligible for garbage collection.
Example 2 · Three ways an object becomes garbage
class Student { String name;
Student(String name) { this.name = name; }}
public class GarbageTraceDemo { static void printTopper() { Student temp = new Student("Ravi"); System.out.println("Topper: " + temp.name); } // Ravi's object: garbage after return
public static void main(String[] args) { Student a = new Student("Asha"); Student b = new Student("Bala"); System.out.println(a.name + ", " + b.name);
a = new Student("Chitra"); b = null; printTopper();
Student c = a; // no new object, a second reference a = null; // Chitra is still reachable through c System.out.println("Still here: " + c.name); }}Asha, Bala Topper: Ravi Still here: Chitra
What this code does
- Asha's
Studentloses its only reference whenais reassigned, Bala's whenbis set tonull, and Ravi's whenprintTopperreturns andtempdisappears. - Setting
a = nulldoes not make Chitra garbage, becausecstill refers to the same object. An object is garbage only when no reference to it remains.
Three everyday ways an object becomes garbage:
- You point the only variable at a different object:
a = new Student("Chitra");. - You set the only reference to
null:b = null;. - A method returns, and its local variables disappear with its stack frame. Eligible does not mean "deleted now". The memory is reclaimed at the next collection that looks at that part of the heap, which may be milliseconds or minutes later.
Trace the code
When does an order become garbage?
Variables
- a
- Order 101
Output
(nothing printed yet)Line 4Order 101 is created. Its only reference is the variable a.
System.gc() is only a request
System.gc() asks the JVM to run a garbage collection. The Javadoc calls it a suggestion: the JVM may run a big collection, a smaller one, or nothing at all.
Example 3 · Memory before and after System.gc()
public class GcRequestDemo { static long usedMb() { Runtime rt = Runtime.getRuntime(); return (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024); }
public static void main(String[] args) { int[][] marks = new int[200][]; for (int i = 0; i < marks.length; i++) { marks[i] = new int[50_000]; // about 200 KB per array, 40 MB in all } System.out.println("Used with marks loaded: " + usedMb() + " MB");
marks = null; // all 200 arrays are now garbage System.out.println("Used after marks = null: " + usedMb() + " MB");
System.gc(); // only a request System.out.println("Used after System.gc(): " + usedMb() + " MB"); }}Used with marks loaded: 40 MB Used after marks = null: 40 MB Used after System.gc(): 0 MB
What this code does
- Setting
marks = nullmakes 40 MB eligible, but the used memory does not change: nothing is reclaimed until a collection runs. - Here the JVM (HotSpot, Java 21, G1) honoured the request and the number dropped to almost 0. Your numbers will differ, and another JVM or option may ignore the call.
Example 4 · Watching what System.gc() really does
java -Xlog:gc GcRequestDemojava -Xlog:gc -XX:+DisableExplicitGC GcRequestDemo[0.019s][info][gc] Using G1 [0.123s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 22M->21M(118M) 12.828ms [0.135s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 35M->35M(118M) 8.184ms Used with marks loaded: 40 MB Used after marks = null: 40 MB [0.157s][info][gc] GC(2) Pause Full (System.gc()) 40M->0M(8M) 3.228ms Used after System.gc(): 0 MB ... [0.015s][info][gc] Using G1 [0.121s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 22M->21M(118M) 12.180ms [0.134s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 35M->35M(118M) 8.615ms Used with marks loaded: 40 MB Used after marks = null: 40 MB Used after System.gc(): 40 MB
What this code does
-Xlog:gcprints one line per collection (Java 9 and later). The linePause Full (System.gc())shows that the request became a full, whole-heap collection with the program paused.- With
-XX:+DisableExplicitGCthe same call does nothing: no full GC line, and the 40 MB stays until the collector decides on its own. The "..." marks one trimmed log line.
On HotSpot (the JVM inside standard JDK builds) with the G1 collector, the default on most machines since Java 9, System.gc() normally runs a full GC: a collection of the whole heap while your program is paused. Started with the option -XX:+DisableExplicitGC, the same call does nothing. So never use System.gc() to "save memory" in real code. The collector already runs when it is needed, usually at a better moment than you would pick. The demos in this module call it only to make a collection visible.
finalize() is deprecated (Java 9) and marked for removal (Java 18)
finalize() is a method of Object that the collector may call on an object before reclaiming it. It was meant for cleanup, such as closing a file. It was deprecated in Java 9 and marked for removal in Java 18.
javac FinalizeDemo.javaFinalizeDemo.java:3: warning: [removal] finalize() in Object has been deprecated and marked for removal
protected void finalize() {
^
1 warningThe problems are serious. Nobody knows when finalize() runs, and it may never run at all, for example when the program ends first. Objects with a finalize() method also take longer to collect, and the method can even make the object reachable again.
Close files, connections and readers yourself, with a close() method and try-with-resources. Java 18 and later can switch finalization off with java --finalization=disabled, which shows whether a program secretly depends on it.
Example 5 · finalize() that never runs
class TempFile { String name;
TempFile(String name) { this.name = name; }
@Override protected void finalize() { System.out.println("Deleting " + name); // cleanup we hoped for }}
public class FinalizeDemo { public static void main(String[] args) { for (int i = 1; i <= 3; i++) { new TempFile("report-" + i + ".tmp"); // garbage at once } System.out.println("main ends"); }}main ends
What this code does
- All three
TempFileobjects are garbage right away, yet no "Deleting" line appears. The program ended before any collection ran, sofinalize()was never called and the cleanup never happened. - The JDK 21
javacwarns[removal]when you overridefinalize()(see the command above). The fix is aclose()method called through try-with-resources, which always runs at a known moment.
Next step
Check your understanding
12 quick questions