Australian cloud for business software — built and run in Sydney since 2002

NetLeverage
NetLeverage

java.lang.OutOfMemoryError: Java heap space - tell a small heap from a leak, then capture a heap dump

Technical article
Troubleshooting

About this article: This article is reviewed against the cited sources. This is source research, not lab validation. Check the stated versions and your own requirements before making changes.

When a Java application or Tomcat logs java.lang.OutOfMemoryError: Java heap space, the JVM could not allocate an object in the Java heap. Oracle's JDK 21 guide lists "Detail Message: Java heap space" under the java.lang.OutOfMemoryError error; it does not print the two joined. The joined form is what a log shows, because in OpenJDK 21 (tag jdk-21+35) Throwable.toString writes the class name, a colon and a space, then the message, and the JVM sets the message Java heap space for this failure. Oracle's guide says this "does not necessarily imply a memory leak": the heap may simply be sized too small for what the application legitimately holds. It can also mean the application keeps references to objects it no longer needs. Read the detail message after the colon first, because other messages mean other memory areas. Then check the configured maximum and capture a heap dump at the next failure.

What the error means

Oracle's "Troubleshoot Memory Leaks" page for JDK 21 describes the error as the garbage collector being unable to "make space available to accommodate a new object" with the heap unable to expand further. A stack trace is printed when it is thrown, and a detail message is appended to say which memory area is full. For Java heap space the page names two possibilities: the specified (or default) heap size is insufficient, or the application "is unintentionally holding references to objects". It adds a third: heavy use of finalizers, where objects wait for a finalizer thread that cannot keep up.

The maximum heap is set with -Xmx. The java command page says the default "is chosen at runtime based on system configuration", and that -Xmx is equivalent to -XX:MaxHeapSize.

Other detail messages on the same page have different causes: GC Overhead limit exceeded (the collector runs most of the time and recovers little), Metaspace, Compressed class space, Requested array size exceeds VM limit, and request size bytes for reason. Out of swap space? (a native allocation failed). Raising the heap is the page's action for Java heap space and GC Overhead limit exceeded; for Metaspace it names MaxMetaspaceSize.

Likely causes

Cause What you see How to confirm
Maximum heap too small for the live data Slowing, repeated full collections, then the error at busy times MaxHeapSize is low, and the heap in use after a full collection sits near it
A leak (references kept) Heap use after full collections climbs over days under steady load Oracle: a live set that "increases over time" in a stable state is a strong sign; a heap dump shows what holds it
One oversized request or result The error follows one action, and the stack trace shows the allocating code The trace in the log; the same action fails every time
A finalizer backlog Objects pending finalization grow GC.finalizer_info through jcmd
A different memory area, or a heap failure with a longer message The detail message is not exactly Java heap space; the OpenJDK source also sets Java heap space: failed reallocation of scalar replaced objects and Java heap space: failed retryable allocation The whole text after the colon

Prove the cause before changing anything

All of these read only.

1. Find the exact line in the application log. Note the detail message, the time and the first frames of the stack trace.

2. List the JVMs and pick the process. jcmd must run on the same machine as the JVM, with the same effective user and group as the one that started it, per its page.

jcmd -l

3. Read the options and the maximum heap. VM.command_line prints the command line used to start the JVM, and VM.flags prints the VM flag options and their current values. Both are marked Impact: Low.

jcmd 4120 VM.command_line
jcmd 4120 VM.flags

Find -Xmx in the first and MaxHeapSize in the second. The java page gives the -Xmx size "in bytes"; our own reading is that MaxHeapSize is shown in bytes too. A good sign is a maximum well above what the application needs; a bad sign is a value close to the size of the data it keeps.

4. Read the heap and the finalizer queue. Both are marked Impact: Medium on the jcmd page.

jcmd 4120 GC.heap_info
jcmd 4120 GC.finalizer_info

The jcmd page also lists GC.class_histogram and GC.heap_dump, both marked Impact: High, depending on heap size and content. Treat both as disruptive on a busy server. GC.heap_dump requests a full collection unless -all is given, so a dump taken by hand can pause the application. Our own reading: the file it writes is of the order of the live heap.

5. Check the trend, not one reading. Oracle's page says to watch "the live set": the heap in use after a full collection. A line that is flat but high is a sizing problem. A line that keeps rising under steady load suggests a leak. The page names GC logs (-Xlog), JConsole and JDK Mission Control for this. Logging needs a startup option, so it belongs to the fix below.

Fix

Choose by what the checks showed. If the detail message is Java heap space, our own advice is that the next failure should leave a heap dump and a GC log, so start there. Only if cause 1 was proved, raise -Xmx in the same edit. The other detail messages need their own action, as the Oracle page describes; the heap options below do not address them.

The java command page documents -XX:+HeapDumpOnOutOfMemoryError, which writes the heap to a file when the error is thrown (off by default), and -XX:HeapDumpPath=path, which sets the file. It also documents -Xlog:gc:filename for GC logging.

For Tomcat, RUNNING.txt says memory settings belong in CATALINA_OPTS, set in bin/setenv.sh (or setenv.bat on Windows), and warns "Do not use JAVA_OPTS to specify memory limits". The stop and start scripts it names are shutdown.sh and startup.sh.

RUNNING.txt says "By default the setenv script file is absent", so there are two cases. If bin/setenv.sh already exists, save it first. If it does not exist, there is nothing to save, and the file you create is the change. Check which case applies with a read-only listing:

ls -l /opt/tomcat/bin/setenv.sh

If the file exists, first save the current state:

cp -p /opt/tomcat/bin/setenv.sh /opt/tomcat/bin/setenv.sh.2026-12-03

Disruptive step: the next change edits the Java options of the Tomcat instance and then stops and starts Tomcat. Every request in flight is dropped and every session held in memory is lost. Our own reading: a heap dump written later can approach the size of the heap and can contain passwords and customer data, so the folder needs the space and restricted access. Raising -Xmx makes the JVM take more memory from the server.

Edit setenv.sh (or create it, if it was absent) so that the value of CATALINA_OPTS includes the options below. Our own advice: if the file already sets CATALINA_OPTS, add these options to that value and keep the options already there, rather than adding a second assignment. The folder /var/log/java must already exist and be writable by the account running Tomcat; creating it is a change of its own and is not covered here.

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/log/java/java_heapdump.hprof -Xlog:gc:/var/log/java/gc.log

Only if cause 1 was proved, add one more option to the same value, here for a 3 GiB maximum:

-Xmx3g

Then stop Tomcat with its script:

/opt/tomcat/bin/shutdown.sh

Our own reading: the script only sends the stop command, so the process can outlive it. Wait until the old process has gone, which jcmd -l no longer lists, before the next command, because a start that overlaps the old process can fail on its ports. Then start Tomcat:

/opt/tomcat/bin/startup.sh

Only if you need to back out, run only the case that applies below. Each case says first what it changes.

Disruptive step: the next command puts back the saved setenv.sh. Tomcat then has to be stopped and started again to use it, and that restart drops every request in flight and every session held in memory. Run it only if setenv.sh existed before the change.

cp -p /opt/tomcat/bin/setenv.sh.2026-12-03 /opt/tomcat/bin/setenv.sh

Disruptive step: the next command deletes the setenv.sh you created, which restores the default of no setenv script. No copy of the deleted file is kept, so first check with ls that the file is the one you created. Tomcat then has to be stopped and started again, which drops every request in flight and every session held in memory. Run it only if setenv.sh did not exist before the change.

rm /opt/tomcat/bin/setenv.sh

After either case, stop Tomcat with /opt/tomcat/bin/shutdown.sh, wait until the old process has gone in the same way, then start it with /opt/tomcat/bin/startup.sh.

Then run jcmd <pid> VM.command_line with the new process ID; the options of the earlier setup should be back, and without a setenv script the dump and logging options should be absent.

For a Windows service, Tomcat's service page lists --JvmMx as the maximum memory pool size in MiB and ++JvmOptions for other options; those are changed with the service tool rather than setenv.

Example (illustrative): On app01, jcmd 4120 VM.flags shows MaxHeapSize of 1073741824 bytes (1 x 1,073,741,824, so 1 GiB), the -Xmx1g from an existing setenv.sh that the administrator saved first. The GC log shows the heap in use after full collections sitting at about 950 MiB all day, flat, with the error at the busiest hour. That is a sizing problem, not a leak. The server has 8 GiB. The administrator sets -Xmx3g, which is 3 x 1,073,741,824 = 3,221,225,472 bytes, leaving 8 - 3 = 5 GiB for the operating system, Metaspace, thread stacks and other processes. If the line had kept rising, the heap dump would have come first.

Confirm the fix

  1. jcmd <pid> VM.flags shows the new MaxHeapSize, and VM.command_line shows the dump and logging options.
  2. The GC log shows the heap in use after full collections staying flat through a busy period.
  3. No new java.lang.OutOfMemoryError: Java heap space lines. If the error returns, a file now exists at the HeapDumpPath you set.

What to watch afterwards

  • The size of the dump and log folder; our own reading is that each dump can approach the size of the heap.
  • The post-collection heap use over weeks. A rising line after a larger heap means the larger heap only delayed a leak.
  • Analysing a dump belongs to a developer who knows the application. Oracle's page calls heap dumps "the most important data to troubleshoot memory leaks".

Risks and limits

  • These commands have not been run or lab-tested.
  • A bigger heap does not fix a leak; it postpones the error.
  • The JVM can use more memory than -Xmx: Metaspace, thread stacks and native allocations sit outside the heap, which Oracle's page describes for the other detail messages.
  • Our own advice: heap dumps hold the application's data, so treat the file as sensitive.
  • The options and messages are those of JDK 21 documentation. Earlier releases may differ.

Sources

  • Troubleshoot Memory Leaks — Oracle, Java SE 21 Troubleshooting Guide, no date shown, accessed 3 December 2026
  • The java Command — Oracle, JDK 21 Specifications, no date shown, accessed 3 December 2026
  • The jcmd Command — Oracle, JDK 21 Specifications, no date shown, accessed 3 December 2026
  • RUNNING.txt — Apache Tomcat source, tag 10.1.62, no date shown, accessed 3 December 2026
  • Throwable.java — OpenJDK source, tag jdk-21+35, no date shown, accessed 3 December 2026
  • universe.cpp — OpenJDK source, tag jdk-21+35, no date shown, accessed 3 December 2026
  • Apache Tomcat 10 — Apache Software Foundation, Windows Service How-To, version 10.1.62, 10 November 2026, accessed 3 December 2026