Reputation: 230366
How deep do I need to go into the call stack before I get a StackOverflowError? Is the answer platform dependent?
Upvotes: 122
Views: 83515
Reputation: 3487
While traversing a tree with huge depth, we could face this
/**
* -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;
}
}
Upvotes: 0
Reputation: 714
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();
}
}
Upvotes: 33
Reputation: 1233
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.
Upvotes: 4
Reputation: 49804
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.
Upvotes: 20
Reputation: 48659
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.
Upvotes: 68