Scrivio Interview library
LeadershipAdvanced7 min read · updated 12 November 2026

Should JVM services in your company crash on OutOfMemoryError or try to keep running? Define the policy and justify it.

Our services should exit on OutOfMemoryError and let the orchestrator restart them, because after an OOM the application's state is uncertain: any thread may have failed halfway through an operation, leaving locks, caches and invariants broken. We set -XX:+ExitOnOutOfMemoryError, capture a heap dump first where it is safe, forbid catching OutOfMemoryError in business code except narrowly around one large allocation, alert on every OOM restart as an incident, and make sure restarts cannot cascade.

Why this question is asked

Every organisation running Java eventually has the argument: one team wants the service to stay up at all costs, another says a service that ran out of memory cannot be trusted. Without a written policy, each team decides differently, and incidents turn into debates. Interviewers ask this question at senior levels to see whether we can reason about correctness under failure, not just availability, and turn that reasoning into a rule a whole company can follow. In this answer, we will look at what really happens inside a JVM after an OOM, state the policy, explain the narrow exception, and cover alerting and the risk of cascading restarts.

1What Happens Inside the JVM After an OOM

OutOfMemoryError is an Error, not an Exception, and it is thrown from whatever allocation happened to fail. That could be in our code, in a framework, in a connection pool, in a logging library or in a JDK class. The thread that gets it unwinds its stack, running finally blocks that may themselves need memory and fail again.

So after an OOM we do not know what was interrupted. A thread might have taken an item out of a queue and died before processing it. A cache might have been half updated, with an index pointing at an entry that was never written. A lock might be held by a thread whose code never reached its unlock, or a pool might count a connection as in use forever. Worst of all, the thread that died may have been a background thread, such as a scheduler or a Kafka consumer's heartbeat thread, and the JVM keeps running without it, looking healthy while doing nothing.

The memory pressure usually remains too. If a leak caused the OOM, the next allocation will fail as well, and the service spends its time in garbage collection, answering slowly or not at all. A process in this state is often worse than a dead one, because load balancers keep sending it traffic.

2The Policy: Exit, Restart, Keep the Evidence

The policy is that every JVM service runs with -XX:+ExitOnOutOfMemoryError. On the first OutOfMemoryError the JVM raises, it exits immediately, and Kubernetes or whatever orchestrator we use starts a fresh instance with clean state. A restart costs seconds; running in an unknown state can cost corrupted data or hours of silent failure.

Before exiting, we want the evidence. With -XX:+HeapDumpOnOutOfMemoryError and a HeapDumpPath on a persistent volume, the JVM writes the heap dump first and then exits. But a heap dump is as large as the live heap and takes time to write, several seconds per gigabyte, so for very large heaps or nodes without enough disk, the standard profile may rely on a continuous JFR recording instead. That is why the policy says capture a dump where it is safe.

Text
# the standard runtime profile for every service
-XX:+ExitOnOutOfMemoryError
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/dumps/ # persistent volume, encrypted, access controlled
-Xlog:gc*:file=/logs/gc.log:time,uptime:filecount=5,filesize=20m
# alternative for debugging the JVM itself: -XX:+CrashOnOutOfMemoryError (core file, hs_err log)
Step throughWhat the JVM does on an OutOfMemoryError
  1. Allocation failsafter a full GC
  2. Write heap dumpHeapDumpOnOutOfMemoryError
  3. Exit the processExitOnOutOfMemoryError
  4. Orchestrator restarts the podclean state
  5. Alert raisedOOM restart is an incident

5 steps in order. Play them, or step through them one at a time.

There is a gap the policy must mention. These flags react only to OutOfMemoryErrors that the JVM itself raises, such as Java heap space or Metaspace. A Direct buffer memory error is thrown by Java library code, so it does not trigger them. For that case, a default uncaught exception handler that logs and exits on any OutOfMemoryError, provided in our shared starter library, closes the gap.

3The Narrow Exception for Catching OutOfMemoryError

Business code is not allowed to catch OutOfMemoryError, or Throwable or Error in a way that swallows it. A catch block that logs and continues defeats the whole policy.

There is one narrow exception. When one specific, very large allocation may fail and we have a sensible fallback, we may catch the error right around that allocation. For example, an image service tries to allocate a 500 MB buffer to process a huge upload; if that fails, it can reject the upload with a clear error. This is safe because the failure is confined: the allocation either happened or did not, no shared state was touched, and the large array that failed was never created, so memory is back to where it was.

Java
byte[] buffer;
try {
buffer = new byte[Math.toIntExact(upload.size())]; // one large allocation, nothing else
} catch (OutOfMemoryError e) {
throw new UploadTooLargeException(upload.size()); // fallback: reject this upload only
}
process(buffer); // outside the try: no hidden catching

The rule for reviewers is simple: the try block contains exactly one allocation and nothing else, and the exception must be written down in the review. Even better is avoiding the situation with a size check before the allocation, so the catch is only a last line of defence.

4Alerting: An OOM Restart Is an Incident

The danger of exit-and-restart is that it hides problems. A service that restarts every six hours because of a leak looks fine on uptime dashboards. So the policy says every OOM restart raises an alert to the owning team and gets an incident ticket, with the heap dump or JFR file attached. We count restarts by reason, OOM kill, Java OOM and probe failure, and review the trend.

Leading indicators make the alert earlier. Heap occupancy after GC rising steadily over hours, or resident memory approaching the container limit, warns us before the restart happens, which is the time we have to take a dump calmly.

5Making Sure Restarts Do Not Cascade

A single restart is cheap. A synchronised wave of restarts is not. If an OOM is caused by load, for example a traffic peak that every instance sees, then all instances fail at about the same time, and their traffic moves to the survivors, which fail faster. Clients retry, adding more load. This is a cascade, and it can turn a memory bug into an outage.

The policy therefore includes protections. Services have enough replicas and capacity to absorb a few restarts. Clients use timeouts, retries with backoff and jitter, and circuit breakers so they do not hammer a struggling service. Servers shed load early with bounded queues and request limits instead of accepting work they cannot hold in memory. And work held only in memory, such as queued jobs, is either made durable or accepted as lost, because a restart will lose it.

6Follow-up questions

Why not keep running and let the GC recover?

Sometimes the GC does free memory after an OOM, for example if the failing thread was holding a huge temporary object. But we cannot tell from outside whether this happened or whether other threads were left in a broken state. Choosing to continue means betting correctness on luck, while a restart is predictable and cheap.

What about batch jobs that hold hours of work in memory?

For them a restart loses work, so the answer is checkpointing, saving progress regularly so a restart resumes rather than repeats. The policy still applies: an OOM in the middle of a batch is a bug to fix, and continuing in an unknown state could write wrong results, which is worse than starting again.

Is CrashOnOutOfMemoryError better than ExitOnOutOfMemoryError?

CrashOnOutOfMemoryError makes the JVM crash with a fatal error log and possibly a core file, which is useful when investigating the JVM itself. For ordinary services, the core file is large and rarely needed, so we use ExitOnOutOfMemoryError with a heap dump and keep the crash option for special cases.

7Conclusion

In this answer, we defined a policy for OutOfMemoryError. After an OOM, any thread may have failed mid-operation, so locks, caches, queues and background threads may be broken, and the memory pressure usually remains. So every service exits on OOM with -XX:+ExitOnOutOfMemoryError, writes a heap dump first where it is safe, and the orchestrator restarts it. Catching OutOfMemoryError is not allowed except around a single large allocation with a fallback. Every OOM restart is an alert and an incident, and capacity, backoff and load shedding make sure restarts do not cascade.

What to say in the interviewAbout 80 seconds aloud

Open with

My policy is that services crash on OutOfMemoryError and the orchestrator restarts them. The reason is that after an OOM, the state is uncertain. The error is thrown from whichever allocation failed, so any thread could have died halfway through: a message taken off a queue but not processed, a cache half updated, a lock never released, or a background thread like a scheduler gone while the process still looks healthy.

Then, if they want more

The memory pressure is usually still there too, so the service limps along in GC. A restart costs seconds and gives a clean state. Concretely, every service runs with ExitOnOutOfMemoryError and HeapDumpOnOutOfMemoryError to a persistent, access-controlled path, so the dump is written before exit, and for very large heaps we rely on a continuous JFR recording instead.

Because those flags only cover errors the JVM raises, a shared uncaught exception handler covers things like direct buffer OOMs. Catching OutOfMemoryError in business code is forbidden, except around one large allocation with a fallback, such as rejecting a huge upload.

Every OOM restart alerts the owning team and becomes an incident, with alerts on heap after GC trending up so we catch it earlier. And we protect against cascades with spare capacity, client backoff with jitter, circuit breakers and load shedding.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Should JVM services in your company crash on OutOfMemoryError or try to keep running?...": https://scrivio-interview-library.netlify.app/java/jvm-diagnostics/bf07cf4b83/