Memory Leaks in Java

Last Updated : 2 Dec, 2026

A memory leak in Java occurs when objects that are no longer needed remain reachable, preventing the garbage collector from reclaiming their memory.

  • Memory leaks increase memory consumption and can degrade application performance over time.
  • Long-lived references, unbounded collections, and improperly managed caches are common causes of memory leaks.

How Memory Leaks Occur

Java uses automatic garbage collection to reclaim memory occupied by unreachable objects. However, the garbage collector cannot determine whether a strongly reachable object is still useful to the application.

  • Unused objects that remain strongly reachable occupy memory unnecessarily.
  • Continuous accumulation of such objects can eventually cause an OutOfMemoryError.
unused_objects

Example of a Memory Leak

A static collection can cause a memory leak when it retains objects that are no longer required.

Java
import java.util.ArrayList;
import java.util.List;
class Geeks{
    private static final List<String> list = new ArrayList<>();
    public static void main(String[] args){
        for (int i = 0; i < 1000000; i++){

            // Retain objects without removing them
            list.add("Item " + i);
        }
        System.out.println("Stored objects: " + list.size());
    }
}

Output
Stored objects: 1000000

Explanation: The static list retains references to all the added String objects. If these objects are no longer required, their unnecessary retention can cause a memory leak in a long-running application.

Note: This example demonstrates potential memory leakage through object retention. It does not necessarily cause an OutOfMemoryError.

Common Causes of Memory Leaks

  • Static collections that retain unused objects for extended periods.
  • Unbounded caches that store entries without expiration or eviction policies.
  • Event listeners and callbacks that remain registered after they are no longer needed.
  • Improper use of ThreadLocal variables in long-lived threads.

Unclosed files, sockets, and database connections can also cause resource leaks. These are distinct from Java heap memory leaks but may contribute to increased memory consumption.

Effects of Memory Leaks

Continuous retention of unused objects reduces the heap space available for new allocations and can affect application stability.

  • Can increase garbage collection frequency and overhead.
  • May reduce application throughput and responsiveness.
  • Can eventually cause an OutOfMemoryError.

Example: Exhausting heap memory through continuous object allocation.

Java
import java.util.ArrayList;
import java.util.List;
class Geeks{
    public static void main(String[] args){
        List<byte[]> list = new ArrayList<>();
        while (true){

            // Allocate and retain a 1 MiB byte array
            list.add(new byte[1024 * 1024]);
        }
    }
}

Output:

Screenshot-2026-12-01-154633

Explanation: Each iteration allocates a byte array and stores its reference in the list. Since these arrays remain strongly reachable, garbage collection cannot reclaim them during the loop. Eventually, the available heap space becomes insufficient for further allocations.

Note: Run this example only in a controlled environment with a limited heap size, such as -Xmx32m. The exact error message and stack trace may vary depending on the JVM and source code line numbers.

Tools to Detect Memory Leaks

Memory profiling and diagnostic tools help identify increasing heap usage, retained objects, and reference chains that prevent garbage collection.

Tool

Description

VisualVM

Monitors heap usage, garbage collection activity, and object allocation.

Eclipse Memory Analyzer (MAT)

Analyzes heap dumps to identify objects retaining excessive memory.

Java Mission Control (JMC)

Analyzes Java Flight Recorder (JFR) data to investigate memory and performance issues.

JConsole

Monitors JVM memory usage and garbage collection activity.

YourKit Java Profiler

Provides memory profiling, heap analysis, and object retention tracking.

jcmd

Provides JVM diagnostic commands, including heap dump generation.

Generating a Heap Dump

A heap dump captures information about objects in heap memory and their references. The jcmd utility can generate a heap dump for a running Java application.

jcmd <pid> GC.heap_dump heapdump.hprof

Here, pid represents the process ID of the running Java application. The generated heap dump can be analyzed using tools such as Eclipse MAT.

How to Prevent Memory Leaks in Java

  • Remove unused elements from collections when they are no longer required.
  • Configure cache size limits, expiration policies, and eviction strategies.
  • Unregister event listeners and callbacks when they are no longer needed.
  • Use ThreadLocal.remove() when thread-local values are no longer required.
  • Use try-with-resources to close files, streams, and database connections automatically.
  • Monitor heap usage and analyze heap dumps when unexpected memory growth occurs.
  • Avoid unnecessary long-lived references to objects.

Example: Removing unused objects from a collection.

Java
import java.util.ArrayList;
import java.util.List;
class Geeks{
    public static void main(String[] args){
        List<String> list = new ArrayList<>();
        list.add(new String("Java"));
        list.add(new String("Python"));
        list.add(new String("C++"));
        System.out.println("Before clearing: " + list.size());

        // Remove references to all elements
        list.clear();
        System.out.println("After clearing: " + list.size());
    }
}

Output
Before clearing: 3
After clearing: 0

Explanation: The clear() method removes references to all elements from the list. The dynamically created String objects become eligible for garbage collection if no other references keep them reachable. However, the ArrayList may retain its allocated internal capacity.

The trimToSize() method can be used when reducing the ArrayList's unused capacity is necessary.

Comment