2

I wrote the following simple program:

public class Main{
    public static void main(String[] args) throws Exception{
        new Thread(() -> {
            try{
                Thread.sleep(10000);
            } catch(Exception ignored){ }
            throw new OutOfMemoryError("BOOM!");
        }).start();

        while(true){
            System.out.println("Doing some job...");
            try{
                Thread.sleep(1000);
            } catch(Exception ignored){ }
        }

    }
}

Now I run this with options java -XX:OnOutOfMemoryError="kill -9 %p" Main and expect that the program receives SIGKILL the error thrown. But it ends up printing Doing some job... even after OutOfMemoryError was thrown:

Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Exception in thread "Thread-0" java.lang.OutOfMemoryError: BOOM!
        at Main.lambda$main$0(Main.java:11)
        at java.lang.Thread.run(Thread.java:748)
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...

What's wrong with this?

I'm on java 1.8.0_66

I tried to do java -XX:OnOutOfMemoryError='kill -9 %p' Main and java "-XX:OnOutOfMemoryError=kill -9 %p" Main but it still keep working...

I also tried to check it and execute sudo java -XX:OnOutOfMemoryError="echo 233 > /root/oom" Main and expected /root/oom will contain 223, but no file was created. What did I do wrong?

3
  • Possible duplicate of -XX:OnOutOfMemoryError="kill -9 %p" Problem
    – Edwardth
    Jun 3, 2018 at 18:49
  • @Edwardth Just tried it with java "-XX:OnOutOfMemoryError=kill -9 %p" Main and java -XX:OnOutOfMemoryError='kill -9 %p' Main and it didn't work...
    – Some Name
    Jun 3, 2018 at 18:52
  • @Edwardth I tried all of the examples and no one works...
    – Some Name
    Jun 3, 2018 at 18:56

1 Answer 1

5

-XX:OnOutOfMemoryError works only for OutOfMemoryErrors thrown by JVM itself.

User-generated OutOfMemoryErrors does not differ from any other regular Throwable, and they are not treated specially by JVM.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.