Java 调用堆栈的最大深度是多少?

在得到 StackOverflow 错误之前,我需要进入调用堆栈多深?答案平台是否依赖于?

72444 次浏览

堆栈大小可以通过 -Xss命令行开关来设置,但是根据经验,它足够深,如果不是数以千计的调用,就是数以百计的调用。(默认情况下是平台相关的,但在大多数平台上至少有256k。)

如果出现堆栈溢出,99% 的情况下是由代码中的错误引起的。

我在我的系统上测试,没有发现任何常量值,有时堆栈溢出发生在8900次调用之后,有时只有在7700,随机数。

public class MainClass {


private static long depth=0L;


public static void main(String[] args){
deep();
}


private static void deep(){
System.err.println(++depth);
deep();
}


}

比较一下这两个电话:
(1)静态法:

public static void main(String[] args) {
int i = 14400;
while(true){
int myResult = testRecursion(i);
System.out.println(myResult);
i++;
}
}


public static int testRecursion(int number) {
if (number == 1) {
return 1;
} else {
int result = 1 + testRecursion(number - 1);
return result;
}
}
//Exception in thread "main" java.lang.StackOverflowError after 62844

(2)使用不同类的非静态方法:

public static void main(String[] args) {
int i = 14400;
while(true){
TestRecursion tr = new TestRecursion ();
int myResult = tr.testRecursion(i);
System.out.println(myResult);
i++;
}
}
//Exception in thread "main" java.lang.StackOverflowError after 14002

测试递归类的唯一方法是 public int testRecursion(int number) {

当我们穿越一棵深度很大的树时,我们可以面对这个问题


/**
* -Xss10M
* max call stack count 92766
* -Xss100M
* max call stack count 2148286
*/
public class MaxCallStack {
private Integer stackCount = 0;


public static void main(String[] args) {
MaxCallStack maxStack = new MaxCallStack();
maxStack.evaluate();
}


private void evaluate() {
try {
Tree tree = new Tree();
tree.left = tree;
traverse(tree);
} catch (StackOverflowError e) {
System.out.println(String.format("max call stack count %s", stackCount));
}
}


private void traverse(Tree tree) {
stackCount++;
if (tree.left != null) {
traverse(tree.left);
}
if (tree.right != null) {
traverse(tree.right);
}
}


private class Tree {
Tree left;
Tree right;
}
}