What is the maximum depth of the java call stack?

Java

Java Problem Overview


How deep do I need to go into the call stack before I get a StackOverflowError? Is the answer platform dependent?

Java Solutions


Solution 1 - Java

It depends on the amount of virtual memory allocated to the stack.

http://www.odi.ch/weblog/posting.php?posting=411

You can tune this with the -Xss VM parameter or with the Thread(ThreadGroup, Runnable, String, long) constructor.

Solution 2 - Java

I tested on my system and didn't find any constant value, sometimes stack overflow occurs after 8900 calls, sometimes only after 7700, random numbers.

public class MainClass {
	
	private static long depth=0L;
		
	public static void main(String[] args){
		deep(); 
	}
	
	private static void deep(){
		System.err.println(++depth);
		deep();
	}

}

Solution 3 - Java

The stack size can be set with the -Xss command line switch but as a rule of thumb, it is deep enough, hundreds if not thousands of calls deep. (The default is platform dependent, but at least 256k in most platforms.)

If you get a stack overflow, 99% of the time it's caused by an error in the code.

Solution 4 - Java

Compare these two calls:
(1) Static method:

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) Non-static method using a different class:

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

Test recursion class has public int testRecursion(int number) { as the only method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionripper234View Question on Stackoverflow
Solution 1 - JavafinnwView Answer on Stackoverflow
Solution 2 - JavatroyView Answer on Stackoverflow
Solution 3 - JavabiziclopView Answer on Stackoverflow
Solution 4 - JavasixtytreesView Answer on Stackoverflow