Home:ALL Converter>Making sure that Java returns exit code 137 on OutOfMemoryError

Making sure that Java returns exit code 137 on OutOfMemoryError

Ask Time:2022-02-21T20:19:34         Author:Logan Wlv

Json Formatter

I have a use case where I want to make sure that a Java process exits with code 137 in case of OOM issues.

Here some experimentations I did:

public static void main(String[] args) {
    List<byte[]> arr = new ArrayList<>();
    while(true) {
        arr.add(new byte[4096]);
    }
}

MacOs result:

java oom.java
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at Main.main(oom.java:21)
echo $? 
1

So it seemed clear that the JVM answers with exit code 1 in the case of OOM.

So I tried:

public static void main(String[] args) {
    List<byte[]> arr = new ArrayList<>();
    try {
        while(true) {
            arr.add(new byte[4096]);
        }
    } catch (OutOfMemoryError outOfMemoryError) {
        System.exit(137);
    }
}

Which gave the same result. And this option: -XX:+ExitOnOutOfMemoryError which gave exit code 3.

Why System.exit(137) is being ignored? Anyway to achieve that?

Author:Logan Wlv,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/71206193/making-sure-that-java-returns-exit-code-137-on-outofmemoryerror
yy