Skip to lesson

What garbage collection does

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()

NoFreeDemo.javaJava
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);    }}
Output
Tickets booked: 1000000
Total fare: Rs 174500000

What this code does

  • Each loop step creates a Ticket and a String. In the next step t points to a new ticket, so the old one is garbage. Nothing in the code frees it.
  • Run it as java -Xmx16m -Xlog:gc NoFreeDemo and 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.

GC removes the work of freeing memory, not the need to think about it. An object you still point to is never collected, even if you never use it again.

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

GarbageTraceDemo.javaJava
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);    }}
Output
Asha, Bala
Topper: Ravi
Still here: Chitra

What this code does

  • Asha's Student loses its only reference when a is reassigned, Bala's when b is set to null, and Ravi's when printTopper returns and temp disappears.
  • Setting a = null does not make Chitra garbage, because c still 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?

public class OrderTrace {
record Order(int id) {}
public static void main(String[] args) {
Order a = new Order(101);
Order b = new Order(102);
a = new Order(103);
b = null;
Order c = a;
a = null;
System.out.println("Still reachable: " + c.id());
}
}

Variables

a
Order 101

Output

(nothing printed yet)

Line 4Order 101 is created. Its only reference is the variable a.

Step 1 of 7

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()

GcRequestDemo.javaJava
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");    }}
Sample output
Used with marks loaded:  40 MB
Used after marks = null: 40 MB
Used after System.gc():  0 MB

What this code does

  • Setting marks = null makes 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

Terminal
java -Xlog:gc GcRequestDemojava -Xlog:gc -XX:+DisableExplicitGC GcRequestDemo
Sample output
[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:gc prints one line per collection (Java 9 and later). The line Pause Full (System.gc()) shows that the request became a full, whole-heap collection with the program paused.
  • With -XX:+DisableExplicitGC the 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.

Terminal
javac FinalizeDemo.java
Output
FinalizeDemo.java:3: warning: [removal] finalize() in Object has been deprecated and marked for removal
    protected void finalize() {
                   ^
1 warning

The 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

FinalizeDemo.javaJava
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");    }}
Output
main ends

What this code does

  • All three TempFile objects are garbage right away, yet no "Deleting" line appears. The program ended before any collection ran, so finalize() was never called and the cleanup never happened.
  • The JDK 21 javac warns [removal] when you override finalize() (see the command above). The fix is a close() method called through try-with-resources, which always runs at a known moment.

Next step

Check your understanding

12 quick questions