java out of memory then exit

2019-05-21 04:39发布

问题:

I have a piece of software that has to analyze big files. Constraining the input or giving infinite memory is not an option, so I have to live with flying OOMEs. Because the OOME only kills the Thread, my software runs in some crappy state.

From outside everything looks okay because the process is running but on the inside it's braindead.

I would like to pull the plug on it. But how can I do this?

Catching a OOME does not guranteee that the next line of code will be executed. e.g System.exit(9). So the JVM has to notice OOME and destory itself.

Is their some vm option for this?

回答1:

When you get an OOME you can be very low on memory and logging doesn't always work. One way around this is to have a shutdown method which holds some memory it doesn't release until its shutting down.

e.g.

 private static byte[] lastResort = new byte[256*1024];
 public static void handleOOME(OutOfMemoryError oome) {
     lastResort = null;
     try {
        LOG.fatal("Dying after ", oome);
     } finally {
        System.exit(-1);
     }
  }


回答2:

So the JVM has to notice OOME and destroy itself. Is their some vm option for this?

No there is not.

However, I have to question your assumption that you cannot catch an OutOfMemoryError and and immediately call System.exit() in the exception handler.

In practice it should work. The only potential problem is if you have called Runtime.setRunFinalizersOnExit(true) ... and even that is ignored if you exit with a non-zero exit status.

(The caveat about catching OOME's and other random Error exceptions is that the JVM may not be in a fit state to continue executing. But calling System.exit(nonzero) ain't doing that!)



回答3:

You can use -XX:+ExitOnOutOfMemoryError - supported by Java 8 update 92.

You can also use -XX:+CrashOnOutOfMemoryError to get the core dump for further investigation.

You can also use -XX:+HeapDumpOnOutOfMemoryError to generate a heap dump on OOME for further investigation.

Source: this and this.