Sub topic 14
Automatic Memory Management and Garbage Collection
In every earlier chapter, you created objects and never "deleted" them. You made Dog objects, arrays, and strings, used them, and moved on. No cleanup code appeared anywhere. That is not luck. Java manages memory for you, using a system called garbage collection.
This chapter is the final chapter of the tutorial, and it answers a question you may have been carrying since the first one: when does Java throw things away, and how does it decide?
What Memory Is and Why It Needs Managing
Memory is where a running program stores its data. Every object you create with new — every Dog, every array, every String — takes up space in memory. Memory is finite. If a program kept allocating space and never released it, it would eventually run out, slow to a crawl, and crash.
In some languages, the programmer must explicitly release memory. In C and C++, for example, you call functions to free the memory yourself. This is powerful but dangerous. Forget to free memory, and the program leaks it. Free it too early, and the program crashes or corrupts data. These bugs are notoriously hard to find.
Java took a different path: automatic memory management. The programmer creates objects; the runtime system — not the programmer — decides when an object's memory can be reclaimed. The piece of the runtime that does this is the garbage collector.
The Heap and the Garbage Collector
Java divides memory into a few regions, but only two matter for this chapter:
- The stack holds local variables and method call information. Each time a method runs, its parameters and local variables live on the stack. When the method returns, that part of the stack is discarded automatically. You have already been using this: the
int iinside aforloop lives on the stack. - The heap is where objects live. Every time you write
new Dog("Rex"), aDogobject is placed on the heap. Objects stay on the heap until the garbage collector decides otherwise.
The stack cleans itself up automatically as methods return. The heap needs the garbage collector.
The core idea of garbage collection is simple: an object that can never be used again is garbage, and its memory can be reclaimed. Java decides this with a rule called reachability.
Reachability: The One Rule That Matters
An object is reachable if your program can still get to it by following references starting from variables that are definitely still in use — for example, a local variable of a method currently running, or a static field of a class the program is using.
The set of "definitely still in use" starting points is called the garbage collection roots. The collector starts from the roots, follows every reference it finds, marks every object it can reach, and treats everything else as garbage.
Roots: local variables of running methods, static fields, and a few others
|
v
Follow every reference chain from the roots.
Anything not visited is unreachable garbage.Look at this snippet:
Dog d = new Dog("Rex");
d = null;null is a special value meaning "refers to nothing." After the second line, no variable points to the Rex object. It is unreachable. It is not deleted at that instant — but it is now eligible for collection, and the garbage collector will reclaim its memory at some future time.
Three facts about reachability are worth memorizing:
- Reachability is about access, not about use. If the code can reach the object through some reference chain, it is not garbage — even if the program would never actually call a method on it.
- An object being unreachable does not mean it is collected immediately. Collection happens when it happens.
- Unreachable objects cannot "come back." Once nothing can reach an object, no future code can resurrect it (with rare exceptions involving finalizers, which you should never rely on and which we skip in this tutorial).
A Worked Example
The following program creates a million Point objects inside a loop but keeps only one reference. It runs fine, because the collector reclaims the old objects as it goes.
public class GarbageDemo {
public static void main(String[] args) {
Point latest = null;
for (int i = 0; i < 1_000_000; i++) {
latest = new Point(i, i);
// the previous Point is now unreachable
}
System.out.println("Last point: " + latest.x);
}
}
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}Each loop iteration creates a new object. The variable latest then points at the new object, so the old one loses its last reference. A million objects are created; only the last one survives. Try it — the program completes quickly and uses far less than "a million points' worth" of memory at any moment.
How the Collector Works Internally
You do not need to control the garbage collector, but knowing roughly how it works explains a lot of Java's behavior.
Mark and Sweep
The classic algorithm has two phases:
- Mark. Starting from the roots, walk every reference and mark each reachable object.
- Sweep. Walk the heap and reclaim the memory of every unmarked object.
This is the conceptual heart of nearly every collector, though modern ones add refinements.
Generational Collection
One refinement matters in practice: most objects die young. In the example above, a million objects were born and a million died almost immediately. Real programs behave the same way — temporary strings, loop counters-as-objects, intermediate results. So Java's collectors split the heap into generations:
- The young generation holds newly created objects. It is collected often and quickly. Objects that survive several collections are promoted to the old generation.
- The old generation holds longer-lived objects. It is collected less often, because most of its objects are still in use.
This is why allocating many short-lived objects in Java is cheap. It is a designed-for pattern, not a waste to feel guilty about.
Stop the World (Sometimes)
Some collection steps pause your program briefly while the collector works. These pauses are called stop-the-world pauses. Modern collectors keep them very short (often a few milliseconds), but if you have ever heard someone describe a Java application as briefly "freezing," this is one possible cause. Different collectors trade off pause length against total throughput; that tuning is far beyond a first tutorial, but the trade-off itself is worth knowing.
callout tip Do not write code to "help" the garbage collector, such as calling System.gc() to request a collection. It is only a suggestion to the JVM and can actually make performance worse. The collector is usually better at its job than manual hints are.
Memory Leaks Still Happen
A common beginner belief is: "Java has garbage collection, so Java programs cannot leak memory." Not true. The collector only reclaims unreachable objects. If your program accidentally keeps a reachable reference to an object it will never use again, that object is reachable — so it is never collected. That is a memory leak in Java, and it is real.
The classic mistake is a collection (like an ArrayList) that only grows:
import java.util.ArrayList;
import java.util.List;
public class LeakDemo {
// static field: reachable from the roots for the whole program's life
static List<String> history = new ArrayList<>();
public static void main(String[] args) {
for (int i = 0; i < 1_000_000; i++) {
history.add("record " + i); // added, never removed
}
// The list holds a million strings forever.
// The collector cannot reclaim them: the list is reachable.
}
}Nothing here is wrong syntactically, and the program will not crash at this small scale. But the pattern scales badly. The list is reachable through the static field, so the collector must keep every string it references — including the ones the program no longer needs. The fix is to remove items you no longer need (history.clear() or targeted remove calls), or to not hold data longer than necessary.
The habit to build: memory management in Java is not "nothing to think about." It is "one thing to think about" — does my program still hold a reference to this? If yes, it stays. If no, it goes.
Comparing With Manual Memory Management
| Aspect | Manual (C, C++) | Java garbage collection |
|---|---|---|
| Who frees memory | The programmer | The collector, automatically |
| Forgetting to free | Leaks memory | Still possible, but only via stale references |
| Freeing too early | Crashes and corruption | Cannot happen |
| Programming mental load | High | Lower; focus on reachability instead |
| Pause-time behavior | Usually none | Brief collector pauses possible |
The takeaway is a trade-off: Java gives up a little control and occasionally a little pause time, and in exchange removes two entire categories of devastating bugs.
Where You Are Now
This is the last chapter. You began by compiling a Hello, World! program and learning that the JVM runs bytecode on any platform. You then learned variables, operators, control flow, loops, arrays, strings, methods, classes, objects, constructors, and inheritance. This chapter closed the loop: the JVM not only runs your objects, it manages their whole life cycle — birth with new, life on the heap, and quiet reclamation when nothing can reach them anymore.
You now know all the core building blocks of Java. Every larger Java program — libraries, servers, Android apps — is built from exactly these pieces, composed with more classes, more methods, and more care.
Exercise
An object has no references pointing to it. Is it deleted immediately?
Show answer
No. It becomes eligible for garbage collection. The collector reclaims it at some later time of its own choosing.
Exercise
In the LeakDemo example, why does the garbage collector not reclaim the old strings?
Show answer
Because the list they are in is reachable (through a static field, which is a GC root), and the list still references them. Reachable objects are never collected.
Exercise
Your program creates a new String inside a loop, uses it, and never stores it. Is this wasteful in Java?
Show answer
No. Short-lived objects are the normal, well-optimized case. They are allocated in the young generation and collected cheaply. This is a designed-for pattern.