Video in progress
After an OutOfMemoryError, should you leave the JVM running or kill it right away? What policy do you choose for the platform?
I usually choose to kill it right away: -XX:+ExitOnOutOfMemoryError and a heap dump before it. After an OOM the application's state is uncertain, and the orchestrator brings up a clean instance in a few seconds.
📖 Answer
An OOM can occur in any thread, on any allocation. It doesn't fall into catch (Exception), but it does fall into catch (Throwable), and many frameworks log it and carry on. As a result:
- a scheduler thread has died, but the service looks "healthy";
- a
ConcurrentHashMapor cache is left partially updated; - a lock wasn't released, a connection didn't return to the pool;
- the JVM can't get out of Full GC and ends up in a "zombie" state where it barely responds.
That is why the platform default is:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps/
-XX:+ExitOnOutOfMemoryError
There is also CrashOnOutOfMemoryError, which additionally writes an hs_err file and a core dump, but it usually isn't needed.
A few subtle points:
- Writing the dump takes a long time on a big heap. Make sure the liveness probe doesn't kill the pod meanwhile, otherwise a half-written dump is left behind. The dump volume should be larger than the heap.
- The dump contains personal data. Set the storage location, permissions and retention.
ExitOnOutOfMemoryErrorworks only for OOMs inside the JVM, like Java heap and metaspace. When you hit the container limit, the kernel kills the process with SIGKILL (exit 137) and there is no dump.- Repeated OOMs lead to a crash loop. You need an alert on restart count.
There are "self-protecting" services as an exception (for example a gateway that must reject the request and keep working). But even there, limiting memory up front (limits, backpressure) is a better approach than catching the OOM.
Sign up to mark studied questions and save your progress.