How to know about OutOfMemory or StackOverflow errors ahead of time

前端 未结 11 1715
余生分开走
余生分开走 2021-02-15 17:10

In Java, is there a way to know that a StackOverflow error or OutOfMemory exception may happen soon?

The OutOfMemory exception m

11条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-15 17:46

    For StackOverflowError:

    To know the current depth, usually it's either:

    1. using a stateful function (storing the depth in outside the function)
    2. using an accumulator (passing the depth as an argument to the function)

    Knowing the depth it will occur is difficult. There are several factors:

    1. The stack space allocated to the JVM (you can change this with the -Xss option)
    2. The amount of stack space already used
    3. The amount used by the current function.

    Why not try it out using something like this?

    public static void main(String[] args) {
        try {
            recurs();
        } catch (Throwable t) {
            // not a good idea in production code....
        }
    }
    static int depth = 0;
    static void recurs() {
        System.out.println(depth++);
        recurs();
    }
    

    Run it several times. Also try adding dummy variables. It can be seen that even the same code may halt at different depths and adding more variables cause it to end earlier. So yeah, pretty much it's unpredictable.

    I suppose that besides rewriting the algorithm the only option would be to increase the stack space with the -Xss option.

    For OutOfMemoryError, there's the -Xmx option

提交回复
热议问题