java out of memory then exit

会有一股神秘感。 提交于 2019-12-06 09:43:00

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);
     }
  }

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!)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!