Sub topic 12
Understanding `OutOfMemoryError`
This chapter assumes basic Java syntax, object references, and running Java programs from the command line. It also assumes you understand that garbage collection removes objects that are no longer reachable.
OutOfMemoryError (OOME) means the JVM could not satisfy a memory request. The request might be for a Java heap object, class metadata, a direct buffer, or a new thread. The message identifies the memory area that failed.
Common causes and messages
| Message | Usual cause | First place to investigate |
|---|---|---|
| `Java heap space` | Live objects do not fit in the heap | Heap dump and retained objects |
| `GC overhead limit exceeded` | The JVM spends most of its time collecting and frees little memory | Heap growth and allocation rate |
| `Metaspace` | Too much class metadata, often from class-loader leaks | Class loaders and generated classes |
| `Direct buffer memory` | Too many or oversized off-heap NIO buffers | Direct buffer ownership and limits |
| `unable to create native thread` | The operating system cannot provide another thread | Thread count, stack size, and process limits |
Increasing -Xmx can postpone Java heap space, but it does not fix a leak. It can also increase pause times or cause the operating system to terminate the process if physical memory is exhausted.
A heap leak
A memory leak in a garbage-collected language occurs when a program retains references to objects that it no longer needs. The collector sees those objects as reachable, so it cannot reclaim them.
import java.util.ArrayList;
import java.util.List;
public class LeakDemo {
private static final List<byte[]> CACHE = new ArrayList<>();
public static void main(String[] args) {
while (true) {
CACHE.add(new byte[1024 * 1024]);
}
}
}Run it with a small heap:
javac LeakDemo.java
java -Xmx64m LeakDemoThe program eventually reports java.lang.OutOfMemoryError: Java heap space. The static list is reachable from a garbage-collection root. Every array stored in the list therefore remains live.
The same pattern can appear in caches, listener lists, thread-local values, queues, session maps, and application registries. A cache needs an eviction policy, such as a maximum size or expiration time.
A diagnostic workflow
Use a repeatable process rather than changing flags randomly.
- Record the complete error message, JVM version, heap settings, and workload.
- Check whether memory usage grows continuously or only during a short allocation burst.
- Capture a heap dump when the failure occurs.
- Inspect the largest object groups and their retaining paths.
- Check non-heap resources when the message is not
Java heap space.
Enable a heap dump for a future failure:
java -Xmx256m \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=./dumps \
LeakDemoThe dump can be opened with a heap-analysis tool. Look for objects with high retained size. Retained size is the memory that would become reclaimable if an object and everything reachable only through it were removed.
For a running process, first find its process ID, then use jcmd:
jcmd <pid> GC.heap_info
jcmd <pid> GC.class_histogram
jcmd <pid> JFR.start duration=60s filename=memory.jfr settings=profileGC.heap_info shows heap details. GC.class_histogram estimates the number and size of objects by class. Java Flight Recorder (JFR) records allocation and garbage-collection events for later analysis. These commands require suitable permissions and a JDK installation.
Prevention and fixes
Remove stale references, bound caches, close resources, and avoid creating unbounded threads. For legitimate larger workloads, set a deliberate heap size with -Xms and -Xmx, leaving memory for the JVM, native libraries, direct buffers, and the operating system.
StackOverflowError is different. It usually means a thread exhausted its stack through recursion. It is not a heap-capacity error.
Exercise
A service fails with Java heap space, and a static map contains every request ever received. What is the primary fix?
Show answer
Stop retaining completed requests. Remove entries or use a bounded, expiring cache. Increase -Xmx only if the required live data genuinely needs more memory.