How can memory leaks occur in Java even we have automatic garbage collection?

Memory leaks in Java occur when objects that are no longer required remain reachable through active references. Since the Garbage Collector can only remove unreachable objects, these unnecessary references prevent memory from being reclaimed, leading to increased memory consumption over time.

Key Points: • Garbage Collection removes only unreachable objects, not unused but referenced objects. • Memory leaks commonly occur due to static collections, unclosed resources, caches, and event listeners that retain references. • Long-lived objects holding references to short-lived objects can prevent garbage collection. • Memory leaks gradually increase heap usage and may eventually cause OutOfMemoryError. • Proper resource management and removing unused references help prevent memory leaks.

Example: If objects are continuously added to a static List and never removed, they remain referenced throughout the application's lifetime. As a result, the Garbage Collector cannot reclaim their memory.

Code Example:

import java.util.ArrayList;
import java.util.List;

public class MemoryLeakDemo {

    private static final List<Object> cache = new ArrayList<>();

    public static void main(String[] args) {
        while (true) {
            cache.add(new Object());
        }
    }
}

Interview Tip: A concise interview answer is:

"Memory leaks can occur in Java when objects are no longer needed but are still referenced by reachable objects. Since the Garbage Collector only removes unreachable objects, these retained references prevent memory reclamation and can lead to excessive memory usage or OutOfMemoryError."