Sub topic 14
Automatic Memory Management and Garbage Collection
In most of this tutorial, you have created objects with new — for example, Dog d = new Dog("Rex");. But you never had to delete them. In languages like C, the programmer must manually free memory. Java does this for you. This chapter explains how.
What Is Memory, and What Is Garbage?
Memory is where your program stores data while it runs. Every time you create an object with new, Java sets aside a piece of memory to hold it.
Garbage is an object that your program can no longer reach — no variable still points to it, so it can never be used again. Here is how an object becomes garbage:
class Dog {
String name;
Dog(String name) { this.name = name; }
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Rex"); // object is created; d points to it
d = new Dog("Bella"); // d now points to a new object
// The Dog named "Rex" has no variable pointing to it.
// It is now garbage.
}
}After the second assignment, nothing refers to the "Rex" object anymore. In a language without automatic memory management, that memory would be lost until the program exits. In Java, it gets cleaned up automatically.
The Garbage Collector
The garbage collector (GC) is a part of the Java Virtual Machine (JVM) that runs in the background. Its job is simple to state:
- Find all objects your program can still reach, starting from live variables.
- Everything it cannot reach is garbage.
- Reclaim (free up) the memory used by garbage so it can be reused.
You do not call the garbage collector yourself. It decides when to run, usually when the program needs more memory than is currently free.
flowchart TD
A["new Dog('Rex')"] --> B["Variable d points to Rex"]
B --> C["d = new Dog('Bella')"]
C --> D["d points to Bella"]
D --> E["Rex is unreachable"]
E --> F["Garbage collector frees Rex's memory"]caption: An object becomes garbage when no variable can reach it. alt: A flowchart showing a Dog object being created, the variable being reassigned, the old object becoming unreachable, and the garbage collector freeing its memory.
What This Means for You
Automatic memory management removes a whole class of bugs, but it does not remove all responsibility. Keep these rules in mind:
- You never explicitly free objects. There is no
deletein Java. - An object stays alive as long as it is reachable. If a list keeps growing and you never remove old entries, the garbage collector cannot free them. This is called a memory leak — yes, it can happen even with a GC.
- When an object is eligible for collection is not predictable. Do not write code that depends on exactly when an object is destroyed.
- You cannot force garbage collection. Calling
System.gc()only suggests that the JVM run the collector; it may ignore the request.
A Simple Demo
You can watch memory being used and reclaimed. The JVM can report how much memory it is using:
public class GCDemo {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.println("Used memory before: "
+ (rt.totalMemory() - rt.freeMemory()) / 1024 + " KB");
for (int i = 0; i < 1_000_000; i++) {
new Dog("Dog-" + i); // create a million short-lived objects
}
System.out.println("Used memory after: "
+ (rt.totalMemory() - rt.freeMemory()) / 1024 + " KB");
System.gc(); // suggest a cleanup
System.out.println("Used memory after gc(): "
+ (rt.totalMemory() - rt.freeMemory()) / 1024 + " KB");
}
static class Dog {
String name;
Dog(String name) { this.name = name; }
}
}Run it a few times. The numbers vary because the garbage collector runs on its own schedule — which is exactly the point. You create objects; Java cleans up after them. This is the last chapter, and it closes the loop on the full life of a Java object: created with new, used through variables and methods, and recycled automatically when nothing needs it anymore.
Exercise
In the first example, what makes the Dog object named "Rex" become garbage?
Show answer
The variable d was reassigned to a new Dog ("Bella"), so no variable references "Rex" anymore. Unreachable objects are garbage and can be reclaimed by the garbage collector.
Exercise
Can a Java program still have a memory leak even though it has a garbage collector?
Show answer
Yes. If your program keeps reachable references to objects it no longer needs — for example, adding to a list and never removing entries — the GC cannot collect them, so memory use keeps growing.