Fix Java OutOfMemoryError: Java heap space
This error occurs when the JVM cannot allocate more objects in the heap. Increase heap size with -Xmx, optimize memory usage, and profile your application to resolve it.
Symptoms
When running a Java application, you encounter the following error in the console or logs:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap spaceThis may be accompanied by application freezing, crashes, or extremely slow performance. The error can occur in any Java-based application, including web servers (Tomcat, Jetty), desktop apps, or command-line tools.
Root Causes
1. Insufficient Heap Size
The default heap size allocated by the JVM is often too small for memory-intensive applications. For example, the default maximum heap on many systems is 256 MB or 512 MB, which may not suffice for applications handling large datasets, images, or concurrent requests.
2. Memory Leaks
Objects that are no longer needed are inadvertently held in memory, preventing garbage collection. Common causes include:
- Static collections that grow indefinitely
- Unclosed resources (database connections, file streams)
- Listener or observer registrations not removed
- ThreadLocal variables not cleaned up
3. Excessive Data Processing
Loading entire large files, databases, or images into memory without streaming or batching can exhaust the heap.
4. Improper Configuration
Setting -Xms and -Xmx incorrectly, or not setting them at all, can lead to frequent garbage collection and eventual OOM.
Step-by-Step Fix
Step 1: Increase Heap Size
Add JVM arguments to increase the maximum heap size. Use the -Xmx flag followed by the desired size (e.g., -Xmx2g for 2 GB). Also set the initial heap size -Xms to the same value to avoid resizing overhead.
Example for command line:
java -Xms1g -Xmx2g -jar myapp.jarFor Tomcat, edit CATALINA_OPTS in setenv.sh (Linux) or setenv.bat (Windows):
CATALINA_OPTS="-Xms1g -Xmx2g"Step 2: Analyze Heap Dump
If increasing heap doesn't fix the issue, generate a heap dump when OOM occurs:
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/to/dump -Xmx2g -jar myapp.jarAnalyze the dump using tools like Eclipse Memory Analyzer (MAT) or VisualVM. Look for:
- Large object arrays or collections
- Objects with unexpectedly high retention
- Thread stacks holding references
Step 3: Fix Memory Leaks
Based on analysis, address the leak:
- Clear static collections when not needed
- Use try-with-resources for streams and connections
- Remove listeners/observers in
destroy()methods - Nullify large objects after use
Step 4: Optimize Code
- Use streaming APIs (e.g.,
Files.lines()instead ofreadAllLines()) - Process data in chunks or batches
- Use
StringBuilderinstead of string concatenation in loops - Consider using
SoftReferenceorWeakReferencefor caches
Alternative Fixes
- Reduce memory footprint: Use more memory-efficient data structures (e.g.,
ArrayListvsLinkedList, primitives vs wrappers). - Tune garbage collection: Switch to G1GC with
-XX:+UseG1GCand adjust region size. - Increase swap space: Not recommended as it degrades performance.
- Use external caching: Offload data to Redis or Memcached.
Prevention
- Always set
-Xmsand-Xmxfor production applications. - Monitor heap usage with tools like JConsole, VisualVM, or APM solutions.
- Conduct regular code reviews to catch memory leaks early.
- Implement automated testing with memory profiling (e.g., JMH, JUnit with heap assertions).
- Set up alerts for high heap usage in production.
Example Configuration
| Environment | Recommended JVM Args |
|---|---|
| Small app (e.g., CLI tool) | -Xms256m -Xmx512m |
| Web server (Tomcat) | -Xms2g -Xmx4g -XX:+UseG1GC |
| Big data processing | -Xms8g -Xmx16g -XX:+UseParallelGC |
By following these steps, you can effectively resolve and prevent java.lang.OutOfMemoryError: Java heap space in your Java applications.
Was this solution helpful?