3 Things you can do when OutOfMemory happens

In this brief article we will outline three JVM configuration parameters you can add to the JVM to handle a scenario when your application issues an OutOfMemoryError.

The OutOfMemoryError: Java heap space error means thatyour JVM heap size (or the default size, if you rely on defaults) is insufficient for the application. In this article we will not discuss how to troubleshoot a possible memory leak in your application; rather we will learn which JVM options you can include at start up to be reactive when this error happens.

Exiting the application when you hit an OutOfMemory

When there is insufficient space to allocate an object in the Java heap an OutOfMemory Error is thrown. However, the Java process remains active. This might not be desirable in several cases therefore you can configure the JVM to terminate when the garbage collector cannot make space available to accommodate a new object,

Since Java 8 update 92 (8u92) you can add the following option to force the termination of the JVM:

-XX:+ExitOnOutOfMemoryError

This flag, and the ones described below, are still current and supported on Java 21/25 LTS — there is no newer replacement for it.

Finally, don’t confuse the -XX:OnOutOfMemoryError option (described in the next section) with the -XX:OnError option. The OnError option allows to execute a script/command when a fatal error occurs. For example, something is wrong with the JIT, therefore you have attempted to execute invalid code.

Example:

-XX:OnError="pmap %p"

Running a command when you hit the Error

On the other hand, if you prefer to handle the JVM termination with a command or a script file, you can pass the command as an argument to the -XX:OnOutOfMemoryError flag. For example, the following command will issue the ‘kill -9’ command to terminate the ProcessId (%p):

-XX:OnOutOfMemoryError="kill -9 %p"

If you prefer, instead of using a command, you pass as argument a script file:

-XX:OnOutOfMemoryError="/path/quitJava.sh"

Taking an Heap Dump on Error

Next, we would like to account for the option -XX:+HeapDumpOnOutOfMemoryError. This flag tells the JVM to generate a heap dump when a memory allocation cannot be satisfied. There is no overhead in running with this option, it’s fine (or say recommended) to include it also in production systems:

-XX:+HeapDumpOnOutOfMemoryError

To specify a different Path for your Heap Dump, you can use the following argument (note the uppercase XX):

-XX:HeapDumpPath=path

Finally, you can also set the above options programmatically with JVM API. See the following example:

String pid = ManagementFactory.getRuntimeMXBean().getName();
pid = pid.substring(0, pid.indexOf('@'));
String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String fileName = "/tmp/heap_" + pid + "_" + date + ".dump";

HotSpotDiagnosticMXBean bean = ManagementFactory.newPlatformMXBeanProxy(
    ManagementFactory.getPlatformMBeanServer(),
    "com.sun.management:type=HotSpotDiagnostic",
    HotSpotDiagnosticMXBean.class);
bean.setVMOption("HeapDumpOnOutOfMemoryError", "true");
bean.setVMOption("HeapDumpPath", fileName)

Container caveat: don’t forget memory limits

If your application runs in a container (Docker/Kubernetes), these three flags only help once the JVM itself decides it’s out of heap — they don’t protect you from the container’s memory limit killing the process first (OOMKilled) before Java ever gets to throw an OutOfMemoryError. Make sure your heap sizing (-Xmx, or the ergonomics-driven -XX:MaxRAMPercentage) leaves headroom below the container’s memory limit for non-heap JVM memory (metaspace, thread stacks, direct buffers, JIT code cache).

Common errors and FAQ

  • -XX:OnOutOfMemoryError script never runs: a frequent cause is spaces or quoting issues in the command string, or the script not being executable — test the exact command manually first.
  • Heap dump file is huge / fills the disk: on a large heap, -XX:+HeapDumpOnOutOfMemoryError can produce a multi-gigabyte .hprof file — make sure -XX:HeapDumpPath points to a volume with enough free space, especially in containers with a small ephemeral filesystem.
  • Catching OutOfMemoryError in a try/catch doesn’t “fix” the app: the JVM can still be left in an inconsistent state after an OOM (other threads may have failed mid-allocation too) — treat these flags as your primary safety net, not application-level exception handling.
  • Does ExitOnOutOfMemoryError trigger the heap dump too? No — the two flags are independent; if you want both a dump and a clean process exit, enable -XX:+HeapDumpOnOutOfMemoryError together with -XX:+ExitOnOutOfMemoryError (the dump is written before the process exits).

Recommended Articles

Fix java.lang.OutOfMemoryError: Metaspace in Java (2026 Guide)

Fix java.lang.OutOfMemoryError: Metaspace in Java: root causes, JVM flags, jcmd/jconsole/NMT diagnostics, a reproducer, and how to correctly size Metaspace on Kubernetes/OpenShift container images.

Solve Java.lang.OutOfMemoryError: GC overhead limit exceeded with Eclipse MAT and Heap Dump Analysis

Learn how to fix the 'java.lang.OutOfMemoryError: GC overhead limit exceeded' issue by analyzing heap dumps, identifying memory leaks, and upgrading to a newer JDK version.

Extract a Thread Dump from Heap Dump Using VisualVM - A Step-by-Step Guide

Learn how to extract a Thread Dump from a Heap Dump using VisualVM, a free tool for Java application troubleshooting.

Mastering OutOfMemoryError: Direct Buffer Memory in Java - A Comprehensive Guide

Learn how to resolve OutOfMemoryError: Direct buffer memory issues in your Java applications. #Java #WildFly #DirectByteBuffer