18

I know about the -XX:+HeapDumpOnOutOfMemoryError JVM parameter. I also know about -XX:OnOutOfMemoryError="cmd args;cmd args" and that kill -3 <JVM_PID> will request a heap dump.

Question: How can I make sure that I, on OutOfMemoryError, first make a full heap dump and then force a restart (or kill) after the dump is done? Is my best bet -XX:OnOutOfMemoryError="kill -3 %p;sleep <time-it-takes-to-dump>;kill -9 %p"?

Community
  • 1
  • 1
Ztyx
  • 11,411
  • 11
  • 66
  • 105
  • 2
    Wouldn't it be better to monitor the process from without the jvm, and restart it accordingly, e.g. unix script, monitorying system? if the jvm is out of memory i would not want to rely on it to be able to reliably launch a command to restart itself – vikingsteve May 29 '15 at 12:57

3 Answers3

33
java -XX:+HeapDumpOnOutOfMemoryError -XX:OnOutOfMemoryError="kill -9 %p" TestApp

JVM will dump heap first, and then execute OnOutOfMemoryError commands (proof).

apangin
  • 79,047
  • 9
  • 168
  • 200
18

If you just want to shutdown you can use one of the following parameters:

  • -XX:+ExitOnOutOfMemoryError
  • -XX:+CrashOnOutOfMemoryError

The VM arguments were added in Java version 8u92, 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)

flavio.donze
  • 6,077
  • 9
  • 41
  • 69
  • 3
    This may be a silly question, but are these flags mutually exclusive? – gregsilin Apr 06 '18 at 20:02
  • @gregsilin looking at the [changeset in mercurial](http://hg.openjdk.java.net/jdk9/jdk9/hotspot/rev/cbc2d5fbdae1#l2.8), it looks like crashing will be given preference when both options are provided – asgs Apr 24 '20 at 08:28
0

I bet the runtime sets a specific errorlevel on crash. Check for that return code and rerun the program in that case. You should perhaps put that into a script.

The sun jre allows you to heap dump on oome, perhaps openjdk does too.

Marged
  • 9,123
  • 9
  • 45
  • 87