OutOfMemoryError is one of the most serious runtime errors in Java applications. It occurs when the Java Virtual Machine (JVM) cannot allocate enough memory to create new objects or execute operations because the available memory has been exhausted.
This error is commonly seen in enterprise applications, Spring Boot projects, web servers, big data applications, and programs that process large datasets. Understanding why it occurs and how to resolve it is essential for every Java developer.
In this guide, you’ll learn what OutOfMemoryError is, its different types, common causes, practical examples, and step-by-step solutions to fix and prevent it.
What is OutOfMemoryError?
OutOfMemoryError is a subclass of the Error class in Java. It indicates that the JVM has run out of memory and cannot allocate additional objects.
Unlike exceptions, an OutOfMemoryError usually represents a serious problem that cannot be handled gracefully during normal application execution.
Example error:
Exception in thread “main” java.lang.OutOfMemoryError: Java heap space
This means the JVM’s heap memory is full and cannot store additional objects.
Why Does OutOfMemoryError Occur?
The JVM allocates memory for objects, class metadata, thread stacks, and other runtime data. If this memory becomes exhausted and the Garbage Collector (GC) cannot free enough space, Java throws an OutOfMemoryError.
Common reasons include:
- Memory leaks
- Infinite object creation
- Large collections
- Large arrays
- Insufficient JVM heap size
- Too many threads
- Excessive Metaspace usage
- Poor memory management
Types of OutOfMemoryError
Java can throw different types of OutOfMemoryError depending on which memory area is exhausted.
1. Java Heap Space
Most common error:
java.lang.OutOfMemoryError: Java heap space
Occurs when the heap is full.
2. GC Overhead Limit Exceeded
Example:
java.lang.OutOfMemoryError: GC overhead limit exceeded
The Garbage Collector spends most of its time trying to free memory but recovers very little.
3. Metaspace
Example:
java.lang.OutOfMemoryError: Metaspace
Occurs when too many classes are loaded or generated dynamically.
4. Unable to Create New Native Thread
Example:
java.lang.OutOfMemoryError:
unable to create new native thread
Occurs when the application creates more threads than the operating system can support.
5. Direct Buffer Memory
Example:
java.lang.OutOfMemoryError:
Direct buffer memory
Occurs when off-heap direct buffers exceed their configured limit.
Common Causes of OutOfMemoryError
The most common causes include:
- Memory leaks
- Infinite loops creating objects
- Large collections
- Reading huge files into memory
- Creating excessive threads
- Static collections that continuously grow
- Insufficient heap allocation
- Improper caching
Let’s look at the solutions.
Solution 1: Increase JVM Heap Size
If your application genuinely requires more memory, increase the heap size.
Example:
java -Xms512m -Xmx2g Main
Where:
- -Xms = Initial heap size
- -Xmx = Maximum heap size
Example:
java -Xms1g -Xmx4g Main
Avoid setting heap sizes larger than the available physical memory on the machine.
Solution 2: Avoid Memory Leaks
A memory leak occurs when objects are no longer needed but are still referenced.
Incorrect:
List<String> list = new ArrayList<>();
while (true) {
list.add("Java");
}
The list continuously grows and eventually exhausts heap memory.
Better approach:
- Remove unused objects.
- Clear collections when appropriate.
- Avoid unnecessary long-lived references.
Solution 3: Process Large Files in Chunks
Incorrect:
byte[] data = Files.readAllBytes(path);
For very large files, this may consume excessive memory.
Better approach:
Read the file in smaller chunks using buffered streams.
Example:
BufferedReader reader =
new BufferedReader(new FileReader("large.txt"));
Streaming data significantly reduces memory usage.
Solution 4: Limit Collection Size
Collections can grow indefinitely if not managed carefully.
Incorrect:
List<<Employee> employees = new ArrayList();
while(true){
employees.add(new Employee());
}
Correct:
- Remove processed elements.
- Use pagination.
- Process data in batches.
- Choose appropriate collection implementations.
Solution 5: Close Resources Properly
Resources such as database connections, streams, and sockets should always be closed.
Example:
try (
BufferedReader reader =
new BufferedReader(new FileReader("data.txt"))
) {
// Read file
}
Using try-with-resources ensures resources are released automatically.
Solution 6: Reduce Object Creation
Creating unnecessary temporary objects increases memory consumption.
Instead of:
for(int i = 0; i < 1000000; i++){
String text = new String("Java");
}
Reuse immutable objects or constants whenever possible.
Example:
String text = “Java”;
This reduces heap allocations and improves performance.
Solution 7: Monitor Garbage Collection
Garbage Collection automatically frees unused objects.
Enable GC logging:
java -Xlog:gc Main
Analyze:
- GC frequency
- Pause times
- Heap usage
Frequent full GC cycles may indicate memory leaks or insufficient heap space.
Solution 8: Use Memory Profiling Tools
Memory profiling tools help identify leaks and excessive memory usage.
Popular tools include:
- VisualVM
- Java Mission Control (JMC)
- Eclipse Memory Analyzer (MAT)
- JProfiler
- YourKit Java Profiler
These tools can reveal:
- Largest objects
- Retained memory
- Reference chains
- Heap dumps
Solution 9: Limit Thread Creation
Creating thousands of threads consumes significant memory.
Incorrect:
while(true){
new Thread(() -> {
}).start();
}
Better approach:
Use thread pools.
Example:
ExecutorService executor =
Executors.newFixedThreadPool(10);
Thread pools reuse threads and reduce memory consumption.
Solution 10: Optimize Caching
Caching improves performance but can consume excessive memory.
Avoid:
- Unlimited HashMaps
- Infinite caches
- Static collections that never shrink
Instead:
- Set cache size limits.
- Configure expiration policies.
- Remove stale entries regularly.
Solution 11: Tune Metaspace
Applications that dynamically generate many classes may exhaust Metaspace.
Increase Metaspace size:
java -XX:MaxMetaspaceSize=512m Main
Review frameworks that generate proxies or dynamic classes if Metaspace usage grows unexpectedly.
Solution 12: Analyze Heap Dumps
When an OutOfMemoryError occurs, configure the JVM to generate a heap dump.
Example:
java -XX:+HeapDumpOnOutOfMemoryError
The heap dump can then be analyzed using tools like Eclipse MAT to identify:
- Memory leaks
- Large collections
- Unreleased objects
- Dominator trees
Heap dump analysis is one of the most effective ways to diagnose production memory problems.
Real-World Example
Incorrect code:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List list = new ArrayList();
while (true) {
list.add("Java Programming");
}
}
}
Output:
java.lang.OutOfMemoryError: Java heap space
Improved approach:
List list = new ArrayList();
for (int i = 0; i < 1000; i++) {
list.add("Java Programming");
}
list.clear();
The collection is bounded and cleared when no longer needed, preventing unbounded memory growth.
Common Scenarios That Cause OutOfMemoryError
| Scenario | Solution |
|---|---|
| Infinite object creation | Limit object creation |
| Incorrect classpath | Update the classpath |
| Large collections | Remove unused elements and process data in batches |
| Memory leaks | Eliminate unnecessary object references |
| Huge file loading | Read files using streams or buffered readers |
| Small heap size | Increase JVM heap using -Xmx |
| Excessive threads | Use thread pools |
| Unlimited caching | Configure cache size and eviction policies |
| Dynamic class generation | Increase Metaspace and review proxy generation |
Best Practices to Prevent OutOfMemoryError
Follow these recommendations:
- Allocate appropriate heap memory based on application requirements.
- Avoid retaining references to unused objects.
- Process large datasets incrementally instead of loading everything into memory.
- Use efficient data structures.
- Configure cache limits.
- Prefer thread pools over creating new threads repeatedly.
- Monitor heap usage in production.
- Analyze heap dumps after memory-related failures.
- Keep dependencies up to date, as newer versions often include memory optimizations.
- Perform regular performance and load testing.
Frequently Asked Questions (FAQs)
Is OutOfMemoryError an exception?
No. OutOfMemoryError extends the Error class, not the Exception class. It represents a serious JVM problem and is generally not intended to be caught as part of normal application logic.
What is the most common type of OutOfMemoryError?
The most frequently encountered type is:
java.lang.OutOfMemoryError: Java heap space
It occurs when the heap becomes full and the Garbage Collector cannot free enough memory.
How can I fix OutOfMemoryError?
Common solutions include:
- Increasing the JVM heap size.
- Fixing memory leaks.
- Processing data in smaller batches.
- Limiting collection growth.
- Using thread pools.
- Monitoring memory with profiling tools.
- Analyzing heap dumps to identify the root cause.
Can Garbage Collection prevent OutOfMemoryError?
Garbage Collection automatically removes objects that are no longer referenced. However, it cannot reclaim memory from objects that are still reachable. If your application holds unnecessary references or genuinely requires more memory than is available, an OutOfMemoryError can still occur.
Conclusion
OutOfMemoryError is one of the most critical runtime errors in Java and usually indicates that the JVM has exhausted available memory. While increasing the heap size may provide temporary relief, the long-term solution is to identify and eliminate memory leaks, optimize object creation, manage collections carefully, use thread pools, and monitor memory usage with profiling tools. By understanding the different types of OutOfMemoryError and following Java memory management best practices, you can build scalable, efficient, and reliable applications that perform well even under heavy workloads.