Java - shutting down on Out of Memory Error
I've heard very contradictory things on how to best handle this, and am stuck with the following dilemma:
- an OOME brings down a thread, but not the whole application
- and I need to bring down the whole application but can't because the thread doesn't have any memory left
I've always understood best practice is let them go so the JVM can die because the JVM is in an inconsistent state at that point, but that doesn't seem to be working here.
OutOfMemoryError
is just like any other error. If it escapes from Thread.run()
it will cause thread to die. Nothing more. Also, when a thread dies, it is no longer a GC root, thus all references kept only by this thread are eligible for garbage collection. This means JVM is very likely to recover from OOME.
If you want to kill your JVM no matter what because you suspect it can be in an inconsistent state, add this to your java
options:
-XX:OnOutOfMemoryError="kill -9 %p"
%p
is the current Java process PID placeholder. The rest is self-explained.
Of course you can also try catching OutOfMemoryError
and handling it somehow. But that's tricky.
In Java version 8u92 the VM arguments
-
-XX:+ExitOnOutOfMemoryError
-
-XX:+CrashOnOutOfMemoryError
were added, see the release notes.
ExitOnOutOfMemoryError
When you enable this option, the JVM exits on the first occurrence of an out-of-memory error. It can be used if you prefer restarting an instance of the JVM rather than handling out of memory errors.CrashOnOutOfMemoryError
If this option is enabled, when an out-of-memory error occurs, the JVM crashes and produces text and binary crash files.
Enhancement Request: JDK-8138745 (parameter naming is wrong though JDK-8154713, ExitOnOutOfMemoryError
instead of ExitOnOutOfMemory
)