How to catch OutOfMemoryError in JVM and run a script if it's caught?

自古美人都是妖i 提交于 2019-12-30 06:15:49

问题


I have a program that sometimes throw OOME, I understand that there is a flag in the JVM options that I can set and whenever a certain Error/Exception appears (such as OOME) it calls a script I wrote. The script will give the user a notification and will call a the program with a different argument so it won't get OOME again.

does anyone know how to set this flag? what is the JVM options I need to set? I looked everywhere on line and couldn't find the answer.

help me please! Thanks, Aye


回答1:


-XX:OnOutOfMemoryError="cmd args;cmd args"

From: http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html#DebuggingOptions




回答2:


I found one suggestion in a forum: catch the OOME in your application (like directly in main, assuming you're single threaded) and do this in the catch handler:

catch (OutOfMemoryError not_again) {
  System.gc();
  System.runFinalization();
  System.gc();
  System.out.println("Your error message");
}

Cleaning up the heap might free just enough memory to produce a last error message before dying.



来源:https://stackoverflow.com/questions/3821144/how-to-catch-outofmemoryerror-in-jvm-and-run-a-script-if-its-caught

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