Quick revision
The short answer
The policy should be: dump, exit, restart, alert. After an OutOfMemoryError the JVM's state may be inconsistent, so every service runs with -XX:+HeapDumpOnOutOfMemoryError and a HeapDumpPath on persistent, access-controlled storage, plus -XX:+ExitOnOutOfMemoryError so the process ends and the orchestrator restarts the container. We alert on OOM restarts and, earlier, on GC pressure and memory trends, and we size the heap as a percentage of the container limit with -XX:MaxRAMPercentage so metaspace, threads and direct memory have room.
What to remember
In this answer, we designed a fleet policy for OutOfMemoryError: because the JVM's state may be inconsistent afterwards, every service writes a heap dump and exits with -XX:+ExitOnOutOfMemoryError or -XX:+CrashOnOutOfMemoryError so the orchestrator restarts it. Dumps go to persistent, encrypted, access-controlled storage with retention limits because they contain sensitive data. We alert on OOM restarts and earlier on GC pressure and memory trends, and we size the heap with -XX:MaxRAMPercentage so native memory fits inside the container limit.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The policy should be: dump, exit, restart, alert. After an OutOfMemoryError the JVM's state may be inconsistent, so every service runs with -XX:+HeapDumpOnOutOfMemoryError and a HeapDumpPath on persistent, access-controlled storage, plus -XX:+ExitOnOutOfMemoryError so the process ends and the orchestrator restarts the container. We alert on OOM restarts and, earlier, on GC pressure and memory trends, and we size the heap as a percentage of the container limit with -XX:MaxRAMPercentage so metaspace, threads and direct memory have room.
Why this question is asked
In a containerised fleet, one service's out-of-memory problem can show up in three different ways: the JVM throws OutOfMemoryError and limps on, the JVM exits cleanly and restarts, or the kernel's OOM killer terminates the container with no Java-level trace at all. Without a fleet-wide policy, each team discovers these differences during an incident. Interviewers ask this design question to see whether we can turn JVM flags and container settings into a consistent, safe default. In this answer, we will see why restarting is safest, set the JVM flags, decide where heap dumps go and how to protect them, design the alerting, and size memory so that the JVM and the container agree.
1Why Restarting Is the Safest Default
An OutOfMemoryError is thrown in whichever thread happened to ask for memory, at whatever line it was executing. That might be in the middle of updating a cache, inside a library holding a lock, or in a background thread that a connection pool or a Kafka consumer depends on. The thread dies or the operation stops halfway, and the rest of the process keeps running with broken assumptions.
So a JVM that has thrown an OOM is no longer trustworthy. It may serve errors, hang on a lock forever, or, worst of all, serve wrong data while passing health checks. In an orchestrated environment such as Kubernetes, we have a better option: end the process quickly and let the platform start a fresh one, which is back in a known good state in seconds.
2The JVM Flags
HotSpot offers flags that act at the moment of the first OutOfMemoryError. We put them in the shared base image or service template so every service gets them.
- JVM throws OutOfMemoryErrorfirst occurrence
- Write the heap dump
HeapDumpOnOutOfMemoryErrorto /dumps - Exit the JVM
ExitOnOutOfMemoryError, non-zero exit code - Orchestrator restarts the containerfresh JVM in a known state
- Restart counted and alertedOOM restarts metric, ticket or page
- Engineer analyses the dumpfrom protected storage
6 steps in order. Play them, or step through them one at a time.
-XX:+ExitOnOutOfMemoryError makes the JVM exit immediately on the first OOM. -XX:+CrashOnOutOfMemoryError is the alternative: it crashes the JVM deliberately and writes an hs_err crash file, and a core dump if the operating system allows it, which gives more native-level detail but takes longer and produces much larger files. Notice that the heap dump is written before the exit, so we keep the evidence even though the process ends.
One limit matters: these flags react to OutOfMemoryError thrown by the JVM. If the container exceeds its memory limit because of native memory, the kernel kills the process with SIGKILL, and Kubernetes reports OOMKilled with exit code 137. No Java code runs and no heap dump is written. That is why memory sizing, below, is part of the same policy.
3Where Heap Dumps Go and How to Protect Them
A heap dump written to the container's own filesystem disappears when the container is replaced, which is exactly what our policy does next. So the dump path must be a volume that survives restarts: a persistent volume, or a node-local volume from which a sidecar or job uploads files to object storage. The volume must be large enough, since a dump is roughly the size of the used heap, so a 4 GB heap needs about 4 GB of space per dump. We keep only the latest one or two dumps per service and delete older ones automatically, otherwise a crash loop fills the disk.
Dumps also need the same protection as production data, because they contain everything that was in memory: customer records, access tokens, passwords in configuration objects, and session data. So the storage is encrypted and access-controlled, dumps are deleted after a fixed period such as 14 days, and access is logged. For regulated data, some organizations only allow dumps to be analysed inside the production environment. This is a decision to make with the security team before the first incident, not during it.
4Alerting Before and After the OOM
After the fact, we alert on the restart itself. Kubernetes exposes restart counts and the last termination reason, so we can alert when a container restarts because of an OOM, whether it was the JVM's exit or the kernel's OOMKilled. One restart per day might open a ticket; three restarts in an hour pages the owning team, because it is turning into an outage.
Before the fact, we watch the signals that predict an OOM. The most useful is old-generation or heap usage after garbage collection, which for a leak climbs steadily over hours or days; the time spent in GC as a percentage of wall time; and the container's working set compared with its limit, which catches native memory growth that the heap metrics miss. Micrometer exports the JVM side as jvm.memory.used and jvm.gc.pause, so dashboards and alerts can be standard across the fleet.
5Sizing the Heap Relative to the Container
Modern JVMs read the container's memory limit and size the heap from it. -XX:MaxRAMPercentage sets the maximum heap as a percentage of that limit. The default is 25 percent, which is very conservative, so many teams raise it. But the heap is not the only thing in the container: metaspace, often 100 to 300 MB for a Spring Boot service, thread stacks at about 1 MB per platform thread, direct buffers, the JIT code cache and GC structures all live outside it.
A common fleet default is 70 to 75 percent for the heap, leaving the rest for native memory, then tuned per service from measurements. For example, a 2 GB container with 70 percent gives a 1.4 GB heap and leaves about 600 MB for everything else. A service using Netty with many direct buffers, or one with hundreds of threads, may need a lower percentage or explicit limits such as -XX:MaxDirectMemorySize.
| Part | Approximate size | Controlled by |
|---|---|---|
| Java heap | 1,400 MB | -XX:MaxRAMPercentage=70 |
| Metaspace | 150 MB | classes loaded; -XX:MaxMetaspaceSize to cap |
| Thread stacks | 200 threads x 1 MB = 200 MB (reserved) | -Xss and thread count |
| Direct buffers, code cache, GC | about 200 MB | -XX:MaxDirectMemorySize and others |
| Headroom | about 50 MB | keeps the kernel OOM killer away |
6Follow-up questions
Why not let the JVM keep running and just alert?
Because after an OOM, threads may have died and locks may be held, so the process can keep answering health checks while doing wrong or no work. A clean restart is predictable; a broken JVM that looks alive is the hardest kind of incident to diagnose.
What if a service is in a crash loop because of OOM on startup?
Then restarts do not help, and the restart alert fires quickly. Kubernetes will back off between restarts. The heap dump from the first failure is the key evidence, which is why we keep at least one, and the usual causes are a container limit set too low or a large cache loaded eagerly at startup.
Does ExitOnOutOfMemoryError affect graceful shutdown?
Yes, it exits immediately without running shutdown hooks in the usual orderly way, so in-flight requests fail. That is accepted, because a JVM after OOM cannot be trusted to shut down cleanly anyway. Clients should retry idempotent requests, and the load balancer moves traffic to other replicas.
7Conclusion
In this answer, we designed a fleet policy for OutOfMemoryError: because the JVM's state may be inconsistent afterwards, every service writes a heap dump and exits with -XX:+ExitOnOutOfMemoryError or -XX:+CrashOnOutOfMemoryError so the orchestrator restarts it. Dumps go to persistent, encrypted, access-controlled storage with retention limits because they contain sensitive data. We alert on OOM restarts and earlier on GC pressure and memory trends, and we size the heap with -XX:MaxRAMPercentage so native memory fits inside the container limit.
Open with
My policy is dump, exit, restart, alert. After an OutOfMemoryError the JVM state may be inconsistent: the error hits whichever thread asked for memory, so threads may have died, locks may be held and updates may be half done.
Then, if they want more
So every service, through the base image, runs with HeapDumpOnOutOfMemoryError and a HeapDumpPath, and ExitOnOutOfMemoryError, or CrashOnOutOfMemoryError if we want a crash file and core dump. The JVM writes the dump, exits, and Kubernetes restarts the container in a clean state.
The dump path must be a volume that survives the restart, sized for the heap, with only the latest dumps kept. And because heap dumps contain customer data, tokens and secrets, they go to encrypted, access-controlled storage with a short retention and logged access, agreed with security in advance.
For alerting, I alert on OOM restarts, both the JVM exit and kernel OOMKilled, with a ticket for a single restart and a page for repeated ones, and earlier on heap after GC trending up, GC time, and the container working set against its limit.
Finally, I size the heap relative to the container with MaxRAMPercentage, typically around 70 percent as a starting point, because metaspace, thread stacks and direct memory live outside the heap. If those overflow the container, the kernel kills the process with no heap dump at all.
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.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
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 "What should the fleet-wide policy be when a JVM throws OutOfMemoryError in a...": https://scrivio-interview-library.netlify.app/java/exceptions/2d25966687/