How to make Java application kill itself when it has an OutOfMemoryError
Environment
- Java
- JBoss
Issue
- How can you make a Java application such as JBoss kill itself when it runs out of memory
Resolution
-
If you use JDK8 update 92 or later, add Java option
-XX:+ExitOnOutOfMemoryErrorinstead of-XX:OnOutOfMemoryError.-XX:+ExitOnOutOfMemoryErrorcan be applied to both Windows and Linux environments.kill -9can only be run in a Linux environment. -
Add this Java option (e.g. to JAVA_OPTS)
-XX:OnOutOfMemoryError="kill -9 %p" -
If you want to specify it to JAVA_OPTS in run.conf or standalone.conf, add the following:
JAVA_OPTS="$JAVA_OPTS -XX:OnOutOfMemoryError=\"kill -9 %p\"" -
For EWS tomcat, the easiest way to have this applied would be to edit it the command that launches tomcat, for instance in catalina.sh:
$_RUNJAVA "$LOGGING_CONFIG" "-XX:OnOutOfMemoryError=\"kill -9 %p\"" $JAVA_OPTS $CATALINA_OPTS \ -Djava.endorsed.dirs="$JAVA_ENDORSED_DIRS" -classpath "$CLASSPATH" \ -Dcatalina.base="$CATALINA_BASE" \ -Dcatalina.home="$CATALINA_HOME" \ -Djava.io.tmpdir="$CATALINA_TMPDIR" \ org.apache.catalina.startup.Bootstrap "$@" start \ >> "$CATALINA_OUT" 2>&1 & -
If applying this option to the jboss CLI, the following execs should be changed to evals for the space in the option to be handled appropriately:
if [ "x$LOG_CONF" = "x" ]; then exec "$JAVA" $JAVA_OPTS -Dlogging.configuration=file:"$JBOSS_HOME"/bin/jboss-cli-logging.properties -jar "$JBOSS_HOME"/jboss-modules.jar -mp "${JBOSS_MODULEPATH}" org.jboss.as.cli "$@" else echo "logging.configuration already set in JAVA_OPTS" exec "$JAVA" $JAVA_OPTS -jar "$JBOSS_HOME"/jboss-modules.jar -mp "${JBOSS_MODULEPATH}" org.jboss.as.cli "$@" fi -
Note that automatically killing the server on OutOfMemory can be dangerous. If there's a particular request that asks for an unusually large amount of memory, it would trigger the kill when otherwise that request would just fail and the server would continue working normally. And that request could then failover to the other servers and do the same, causing a site-wide outage due to this setting.
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.