How do I make the JVM exit on ANY OutOfMemoryException even when bad people try to catch it

后端 未结 10 504
醉梦人生
醉梦人生 2020-12-09 16:32

An OOME is of the class of errors which generally you shouldn\'t recover from. But if it is buried in a thread, or someone catches it, it is possible for an application to g

相关标签:
10条回答
  • 2020-12-09 16:49

    One more thing I could think of (although I do not know how to implement it) would be to run your app in some kind of debugger. I noticed, that my debugger can stop the execution when an exception is thrown. :-)

    So may be one could implement some kind of execution environment to achieve that.

    0 讨论(0)
  • 2020-12-09 16:50
    1. edit OutOfMemoryError.java, add System.exit() in its constructors.

    2. compile it. (interestingly javac doesn't care it's in package java.lang)

    3. add the class into JRE rt.jar

    4. now jvm will use this new class. (evil laughs)

    This is a possibility you might want to be aware of. Whether it's a good idea, or even legal, is another question.

    0 讨论(0)
  • 2020-12-09 16:50

    Only thing I can think of is using AOP to wrap every single method (beware to rule out java.*) with a try-catch for OOME and if so, log something and call System.exit() in the catch block.

    Not a solution I'd call elegant, though...

    0 讨论(0)
  • 2020-12-09 16:53

    Solution:

    On newer JVMs:

    -XX:+ExitOnOutOfMemoryError
    to exit on OOME, or to crash:
    
    -XX:+CrashOnOutOfMemoryError
    

    On Older:

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

    Definition: Run user-defined commands when an OutOfMemoryError is first thrown. (Introduced in 1.4.2 update 12, 6)

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

    An example that kills the running process:

    -XX:OnOutOfMemoryError="kill -9 %p"
    
    0 讨论(0)
  • 2020-12-09 16:53

    One possibility, which I would love to be talked out of, is have a stupid thread thats job is to do something on the heap. Should it receive OOME - then it exits the whole JVM.

    Please tell me this isn't sensible.

    0 讨论(0)
  • 2020-12-09 16:57

    You could use the MemoryPoolMXBean to be notified when a program exceeds a set heap allocation threshold.

    I haven't used it myself but it should be possible to shut down this way when the remaining memory gets low by setting an allocation threshold and calling System.exit() when you receive the notification.

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