2011-01-19 30 views
78

我得到StackOverflowError之前需要進入調用堆棧多深?答案平臺是否依賴?Java調用堆棧的最大深度是多少?

+1

密切相關:http://stackoverflow.com/questions/794227/how-to-know-about-outofmemory-or-stackoverflow-errors-ahead-of-time – finnw 2011-01-19 10:35:13

+0

由於這是一個很好的問題,我已經將標題更新爲我認爲與意義更加明確相關的內容。 (以前我以爲你可能指的是你在運行時捕獲的*特殊堆棧的深度)。如果您不同意,請隨時更改。 – 2011-01-19 11:28:24

+0

@Andrzej - 沒有異議。 – ripper234 2011-01-19 11:55:16

回答

19

堆棧大小可以使用命令行開關-Xss進行設置,但作爲一個經驗法則,它足夠深入,深度數以百計(如果不是數千次)。 (默認值是與平臺相關的,但至少在大多數平臺256K)

如果你得到一個堆棧溢出的它是由在代碼中的錯誤導致99%的時間。

21

我測試了我的系統上,並沒有發現任何恆定值,有時棧有時只有後7700,隨機數後8900個調用發生溢出。

public class MainClass { 

    private static long depth=0L; 

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

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

} 
2

比較這兩個調用:
(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) {作爲唯一的方法。