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

后端 未结 2 1220
醉酒成梦
醉酒成梦 2021-01-04 21:33

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

相关标签:
2条回答
  • 2021-01-04 22:03

    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.

    0 讨论(0)
  • 2021-01-04 22:27

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

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

    0 讨论(0)
提交回复
热议问题