How to execute commands and script on OutOfMemoryError?

Solution Verified - Updated

Environment

  • OpenJDK 8
  • OpenJDK 11

Issue

  • How to execute commands and script on OutOfMemoryError?
  • How to execute commands in case an OutOfMemoryError exception occurs?
  • In case a JVM crash occurs, is there any flag to execute a script?

Resolution


Disclaimer: Links contained herein to an external website(s) are provided for convenience only. Red Hat has not reviewed the links and is not responsible for the content or its availability. The inclusion of any link to an external website does not imply endorsement by Red Hat of the website or their entities, products or services. You agree that Red Hat is not responsible or liable for any loss or expenses that may result due to your use of (or reliance on) the external site or content.


OnOutOfMemoryError Flag

As described in Content from docs.oracle.com is not included.Oracle Java SE 8 Documentation, the option OnOutOfMemoryError JVM option can be used to specify a command or script to execute when an OutOfMemoryError exception is thrown.

#-XX:OnOutOfMemoryError="<cmd args>; <cmd args>; <script path>"
#Example:
java -XX:OnOutOfMemoryError="java -version" Test

Multiple commands in OnOutOfMemoryError

To execute multiple commands at a OutOfMemoryError exception, one can use ; to add multiple commands, example:

java -XX:OnOutOfMemoryError="java -version" Test; echo "Crash happened"

Fatal Crash - On Error flag

The optionOnOutOfMemoryError is triggered when an OutOfMemoryError exception is thrown. When a fatal crash occurs, i.e. the JVM crashes, as in Interpreting JVM crash file in OpenJDK/OracleJDK, the flag OnError can be used:
Example:

$ java -XX:OnError=echo "Restart JVM"

This option is explained on Content from docs.oracle.com is not included.Oracle Java 8 - Troubleshoot Guide.

Other JVM Options: ExitOnOutOfMemoryError and CrashOnOutOfMemoryError

The update Content from www.oracle.com is not included.JDK 1.8.92 introducted two flags ExitOnOutOfMemoryError and CrashOnOutOfMemoryError.
The table below shows what happens when using each flag:

JVM OptionAction
ExitOnOutOfMemoryErrorThe JVM exits on the first occurrence of an out-of-memory error. It can be used if one prefer restarting an instance of the JVM rather than handling out of memory errors.
CrashOnOutOfMemoryErrorWhen an out-of-memory error occurs, the JVM crashes and produces crash file and core dump file (if core files are enabled)
OnOutOfMemoryErrorWill execute an script on exit
HeapDumpOnOutOfMemoryErrorWill create a heap dump on OutOfMemoryException
Category

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.