I met StackOverflowError in my real project and made simple model that shows the problem. It's test class that calls some recursive method and saves the depth of error.
public class Main {
static int c = 0;
public static void main(String[] args) {
long sum = 0;
int exps = 100;
for (int i = 0; i < exps; ++i) {
c = 0;
try {
simpleRecursion();
} catch (StackOverflowError e) {
sum += c;
}
}
System.out.println("Average method call depth: " + (sum / exps));
}
public static void simpleRecursion() {
simpleMethod();
++c;
simpleRecursion();
}
}
There are two versions of simpleMethod:
public static void simpleMethod() {
}
- It gets either 51K or 59K method calls' depth in tests.
public static void simpleMethod() {
c += 0;
}
- It gets either 48K or 58K method calls' depth in tests.
Why have these realizations got different results? I can't understand what extra data lies in stack in the second case. In my opinion simpleMethod should not influence stack memory because it's not in call chain.