7.3 Memory Leak
← Back to Chapter 7: Garbage Collection & Serialization
What is memory Leak in Java?
Even after GC memory leak can still happen:
Objects are no longer logically needed but are still reachable, so GC cannot remove them.
Example:
static List<User> users = new ArrayList<>();
public void addUser(User user) {
users.add(user);
}
Suppose millions of users are added.
Even if your business logic doesn't need old users anymore:
GC Root
↓
static users
↓
User 1
User 2
User 3
...
User 1,000,000
They are still reachable.
Therefore GC says: "These objects are reachable. I cannot remove them."
Heap keeps growing. Eventually:
OutOfMemoryError
Common causes of Memory Leaks
1. Static collections
static List<Object> list;
2. Objects stored unnecessarily in caches
Especially caches without proper eviction.
3. Listeners/callbacks not removed
Objects remain referenced.
4. ThreadLocal misuse
Very important in server applications.
5. Long-lived objects holding references to short-lived objects
Example:
Singleton
↓
Huge Object
↓
many objects
finalize() and Garbage Collection
Older Java versions had:
protected void finalize()
It was intended to be called before an object was reclaimed.
But: Finalization is deprecated and should not be used in modern Java.
Why? Because it is:
unpredictable
slow
difficult to reason about
can delay memory reclamation
For resource management, use mechanisms such as:
Can an object become eligible for GC without assigning null? ✅
Yes. When the method finishes:
user reference disappears
↓
User object may become unreachable
↓
eligible for GC
Can two objects reference each other and still be garbage? ✅
Yes.
Object A ─────> Object B
↑ |
└──────────────┘
Suppose no GC Root points to A or B.
Then both are unreachable.
Therefore:
A → garbage
B → garbage
What is OutOfMemoryError?
It happens when the JVM cannot satisfy a memory allocation.
Heap is full. Result:
java.lang.OutOfMemoryError
Does OutOfMemoryError always mean a memory leak? ❌
No. Possible reasons include:
1. Actual memory leak
2. Heap too small
3. Application legitimately needs more memory
4. Huge objects
5. Too many objects
6. Poor cache configuration
7. Excessive concurrency
What is StackOverflowError?
Usually caused by excessive method recursion/call depth. Example:
void test() {
test();
}
-Xms and -Xmx
-Xms
Initial/minimum heap size.
-Xmx
Maximum heap size.