Sub topic 9
Memory Leaks in a Garbage-Collected Language
This chapter assumes that you know basic Java syntax, object references, collections, and how to run a Java program from the command line. It also assumes that the JVM uses garbage collection to reclaim objects that are no longer reachable.
What a memory leak means in Java
A memory leak occurs when a program keeps references to objects that it no longer needs. The garbage collector cannot reclaim those objects because they are still reachable from a garbage-collection root.
Common GC roots include:
- Local variables in active stack frames
- Static fields
- Live threads
- JNI references
- Objects referenced by system class loaders
The collector does not understand your application’s business needs. If a static list contains an object, that object is alive from the collector’s point of view, even if your code will never use it again.
A leak usually appears as steadily increasing heap usage. Eventually, garbage collections become more frequent, and the JVM may throw OutOfMemoryError.
A growing static collection
This program keeps allocating one-megabyte arrays:
import java.util.ArrayList;
import java.util.List;
public class LeakDemo {
private static final List<byte[]> CACHE = new ArrayList<>();
public static void main(String[] args) {
while (true) {
CACHE.add(new byte[1024 * 1024]);
}
}
}CACHE is a static field, so it remains reachable for the entire lifetime of the class. Every array added to it also remains reachable. The garbage collector can collect temporary objects created during list growth, but it cannot collect the arrays stored in CACHE.
The program eventually fails with an error similar to:
java.lang.OutOfMemoryError: Java heap spaceThe collection is called CACHE, but it is not a useful cache because it has no size limit and never removes entries.
Common leak patterns
| Pattern | Why objects stay reachable | Typical fix |
|---|---|---|
| Unbounded static collection | A GC root points to every element | Remove entries or limit the collection |
| Listener not deregistered | A long-lived publisher holds the listener | Unregister it when the owner closes |
| Thread-local value | A thread keeps its thread-local data | Call `remove()` when work ends |
| Unbounded cache | Old keys and values remain stored | Add eviction or use a bounded cache |
| Class-loader retention | A long-lived object references application classes | Release references during shutdown |
A collection is not automatically a leak. It becomes a leak when its lifetime is longer than the data it stores and it lacks a removal policy.
Why garbage collection does not prevent leaks
Garbage collection answers this question:
> Can the object be reached from a GC root?
It does not answer this question:
> Does the application still need the object?
The difference is important. A forgotten object may be logically unused but technically reachable.
The dashed links represent application intent. They do not affect reachability. The solid links are enough to keep the arrays alive.
Preventing and confirming leaks
Give every long-lived data structure an ownership rule:
- Who adds entries?
- Who removes entries?
- How large may it become?
- How long should an entry live?
- What happens during shutdown?
For caches, use a maximum size or expiration time. For listeners, provide a matching unregister operation. For resources such as files and database connections, use try-with-resources. Those resources are not ordinary heap objects, and garbage collection is not a reliable release mechanism for them.
To investigate a suspected leak, compare heap usage after repeated full garbage collections. If the used heap after collection keeps growing, some objects are being retained.
You can request a heap dump when the JVM runs out of memory:
java -Xmx256m \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=./dumps \
LeakDemoA heap-analysis tool can show which classes occupy the most memory and the reference paths that retain them. The most useful question is usually not “Which object is large?” but “Which GC root keeps this object reachable?”
Exercise
Why can the garbage collector not reclaim the byte arrays in LeakDemo, and what change would prevent the leak?
Show answer
The static CACHE field remains a GC root and keeps every stored array reachable. Add a bounded size or eviction policy, and remove entries that the application no longer needs.