java.lang.OutOfMemoryError: Java heap space

Fix Java OutOfMemoryError: Java heap space

Programming & Dev Tools Intermediate 👁 0 views 📅 May 25, 2026

This error occurs when the JVM exhausts its heap memory limit. It can be fixed by increasing heap size or optimizing memory usage. Common causes include memory leaks, large data loads, or insufficient allocation.

Symptoms

When a Java application runs out of heap memory, it throws the error java.lang.OutOfMemoryError: Java heap space. Symptoms include:

  • Application crashes or freezes unexpectedly.
  • Error logs showing the OutOfMemoryError exception.
  • Slow performance and excessive garbage collection activity.
  • In web applications, HTTP 500 errors or blank pages.

Root Causes

1. Insufficient Heap Size

The default heap size may be too small for the application's workload, especially for memory-intensive tasks like large data processing, caching, or complex algorithms.

2. Memory Leaks

Objects that are no longer needed remain referenced, preventing garbage collection. Common sources include:

  • Unclosed resources (streams, connections, sessions).
  • Static collections that grow indefinitely.
  • Listener or callback registrations not removed.
  • ThreadLocal variables not cleaned up.

3. Large Data Loads

Loading entire datasets into memory (e.g., large files, database results) can exceed the heap limit.

4. Improper Garbage Collection Tuning

Aggressive GC settings or improper collector choice can lead to fragmentation and inefficient memory usage.

Step-by-Step Fix

Step 1: Increase Heap Size

Add JVM arguments to increase the maximum heap size. For example, to set a 2GB heap:

-Xms512m -Xmx2g

Place these before the -jar argument or in your application server's startup script. Adjust values based on available system memory.

Step 2: Enable Heap Dump on OutOfMemoryError

Add the following JVM argument to generate a heap dump for analysis:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/to/dump

Step 3: Analyze Heap Dump

Use tools like Eclipse MAT, VisualVM, or JProfiler to open the heap dump. Look for:

  • Largest objects and their retainers.
  • Suspiciously large collections or arrays.
  • Objects with unexpected retention paths.

Step 4: Identify and Fix Memory Leaks

Common fixes:

  • Close resources in finally blocks or use try-with-resources.
  • Clear static collections when no longer needed.
  • Remove listeners and callbacks properly.
  • Use weak references for caches (e.g., WeakHashMap).

Step 5: Optimize Data Handling

Process data in chunks instead of loading everything at once. For databases, use pagination or streaming. For files, read line by line.

Step 6: Tune Garbage Collection

Choose an appropriate GC algorithm. For example, for large heaps, use G1GC:

-XX:+UseG1GC -XX:MaxGCPauseMillis=200

Alternative Fixes

  • Reduce object creation: Reuse objects and avoid unnecessary allocations.
  • Increase physical memory: Add more RAM to the server.
  • Scale horizontally: Distribute workload across multiple JVM instances.
  • Use memory-mapped files: For large data sets, leverage off-heap storage.
  • Review third-party libraries: Some libraries may have memory issues; update or replace them.

Prevention

  • Monitor heap usage with tools like JConsole, VisualVM, or Prometheus.
  • Set up alerts for high memory usage.
  • Conduct regular code reviews focusing on resource management.
  • Perform load testing to simulate production workloads.
  • Keep JVM and libraries updated for performance improvements.
  • Document and review JVM arguments for each environment.

By systematically increasing heap size, profiling memory usage, and fixing leaks, you can resolve and prevent OutOfMemoryError in Java applications.

Was this solution helpful?