Fix "java.lang.OutOfMemoryError: Java heap space" (and GC overhead limit exceeded)
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
- java.lang.OutOfMemoryError: GC overhead limit exceeded
- Execution failed for task ':app:mergeDexDebug'. > java.lang.OutOfMemoryError: Java heap space
- java.lang.OutOfMemoryError: Metaspace
- Exception in thread "http-nio-8080-exec-3" java.lang.OutOfMemoryError: Java heap space
- Expiring Daemon because JVM heap space is exhausted
The JVM has no room left in its heap to create an object. If the need is legitimate, raise the maximum size with -Xmx (or org.gradle.jvmargs for a Gradle build); if memory keeps climbing and never drops, it is a leak: take a heap dump with -XX:+HeapDumpOnOutOfMemoryError and analyse it.
What this error means
Java objects live in the heap, whose maximum size is fixed when the JVM starts: by default a quarter of the available RAM, or the value of -Xmx. The garbage collector (GC) frees objects that are no longer referenced. When an allocation fails even after a full GC, the JVM throws OutOfMemoryError: Java heap space. This happens when the data really exceeds the heap (large file, huge query) or when objects stay referenced for no reason (a leak). The GC overhead limit exceeded variant means the JVM spends more than 98% of its time in GC to recover less than 2% of the heap: the symptom is the same.
Common causes
- Heap too small for the load: low
-Xmx, container with little memory, or a Gradle / Android build with the defaultorg.gradle.jvmargs. - Loading everything into memory:
Files.readAllByteson a big file,findAll()on a table with millions of rows, a huge HTTP or JSON response read in one go. - Memory leak: a
staticcollection or unbounded cache that grows on every request, listeners never removed,ThreadLocalvalues not cleaned up in a thread pool. - Loop that creates objects endlessly: recursion over cyclic data, string concatenation or a list filled by mistake in an infinite loop.
Step-by-step fix
-
Identify which JVM runs out of memory
Your application, the Gradle daemon, the Kotlin daemon, Maven or the tests? The thread name and the task in the log tell you. Then check the current heap size.
jcmd # list running JVMs and their PIDs jcmd 12345 GC.heap_info # current heap usage jstat -gcutil 12345 1000 # GC activity every second java -XX:+PrintFlagsFinal -version | grep MaxHeapSize -
Raise the application heap
If the memory need is legitimate, give it more heap. In a container, prefer
MaxRAMPercentage, which follows the container memory limit, over a fixed-Xmx.JAVA_TOOL_OPTIONSapplies to any JVM launched.java -Xms512m -Xmx2g -jar app.jar # in a container java -XX:MaxRAMPercentage=75.0 -jar app.jar # any JVM (tests, tools) export JAVA_TOOL_OPTIONS="-Xmx2g" -
Raise the Gradle / Android build memory
For an error during
mergeDexDebug,compileKotlinor a Gradle build, set the daemon memory ingradle.propertiesat the project root, then restart the daemons with./gradlew --stop. For Maven, useMAVEN_OPTS="-Xmx2g".# gradle.properties org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g -Dfile.encoding=UTF-8 kotlin.daemon.jvmargs=-Xmx2g -
Capture a heap dump
If the problem comes back despite more memory, it is probably a leak. Have the JVM write a dump automatically when the error happens, or take one by hand on a JVM that keeps growing. The
.hproffile contains in-memory data: treat it as sensitive.java -Xmx2g -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/dumps -jar app.jar # manual dump of a running JVM jcmd 12345 GC.heap_dump /tmp/dumps/heap.hprof -
Analyse the dump
Open the
.hproffile in Eclipse Memory Analyzer (MAT), VisualVM or the IntelliJ IDEA profiler. MAT’s "Leak Suspects" report and the "Dominator Tree" view show which objects retain the most memory and the reference chain that keeps them alive. -
Fix the code
Process data as a stream instead of loading everything, paginate queries and bound caches. Once the cause is fixed, memory should level off under load.
// stream a large file line by line try (Stream<String> lines = Files.lines(path)) { lines.forEach(this::process); } // paginate instead of findAll() Page<Order> page = orderRepository.findAll(PageRequest.of(0, 500)); // bounded cache (Caffeine) instead of a static HashMap Cache<String, User> cache = Caffeine.newBuilder().maximumSize(10_000).build();
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Enable
-XX:+HeapDumpOnOutOfMemoryErrorin production so you always have a dump to analyse after an incident. - Monitor the heap and GC (Micrometer, Prometheus, JDK Flight Recorder): memory rising like a staircase without dropping signals a leak well before the crash.
- Run load tests with realistic data volumes before going to production.
Frequently asked questions
Should I disable GC overhead limit exceeded with -XX:-UseGCOverheadLimit?
No: the option only delays the error, the JVM stays stuck in GC and then throws Java heap space. Raise the heap or fix the leak.
What value should I use for -Xmx?
Enough for the real measured peak, with a margin, and always below the RAM or the container limit: the JVM also uses off-heap memory (threads, metaspace, buffers). In a container, 70 to 80% through MaxRAMPercentage is a common starting point.
What is the difference between Java heap space and Metaspace?
Java heap space is about your objects. Metaspace is about class definitions: it fills up when too many classes are loaded (hot redeploys, proxy generation). Raise -XX:MaxMetaspaceSize or look for the classloader leak.
Useful tools for this error
More Java, Kotlin & .NET errors
- Fix "java.lang.NullPointerException: Cannot invoke … because … is null" in Java
- Fix "UnsupportedClassVersionError: compiled by a more recent version of the Java Runtime"
- Fix "Could not resolve all files for configuration" and "Could not find" in Gradle
- Fix "Web server failed to start. Port 8080 was already in use" in Spring Boot
- Fix "Failed to configure a DataSource: 'url' attribute is not specified" in Spring Boot
- Fix "Object reference not set to an instance of an object" (NullReferenceException) in C#
- Fix "lateinit property binding has not been initialized" in Kotlin (Android)