How to increase the Java stack size?

后端 未结 9 1643
余生分开走
余生分开走 2020-11-22 01:59

I asked this question to get to know how to increase the runtime call stack size in the JVM. I\'ve got an answer to this, and I\'ve also got many useful answers and comments

9条回答
  •  青春惊慌失措
    2020-11-22 02:16

    The only way to control the size of stack within process is start a new Thread. But you can also control by creating a self-calling sub Java process with the -Xss parameter.

    public class TT {
        private static int level = 0;
    
        public static long fact(int n) {
            level++;
            return n < 2 ? n : n * fact(n - 1);
        }
    
        public static void main(String[] args) throws InterruptedException {
            Thread t = new Thread(null, null, "TT", 1000000) {
                @Override
                public void run() {
                    try {
                        level = 0;
                        System.out.println(fact(1 << 15));
                    } catch (StackOverflowError e) {
                        System.err.println("true recursion level was " + level);
                        System.err.println("reported recursion level was "
                                + e.getStackTrace().length);
                    }
                }
    
            };
            t.start();
            t.join();
            try {
                level = 0;
                System.out.println(fact(1 << 15));
            } catch (StackOverflowError e) {
                System.err.println("true recursion level was " + level);
                System.err.println("reported recursion level was "
                        + e.getStackTrace().length);
            }
        }
    
    }
    

提交回复
热议问题