1

I specicified `-Xss200k, so the stack size should be 200 kilobytes for each thread. When I create a new thread, it allows me to do a huge amount of nested function calls before StackOverflow arrives. I belive I should get a constant amount of calls for a brand-new thread that has its stack filled with N frames. However, the amount of possible recursive calls varies between runs:

StackOverflowError.... recursiveCalls = 2257
StackOverflowError.... recursiveCalls = 2266
StackOverflowError.... recursiveCalls = 2261
StackOverflowError.... recursiveCalls = 2267
StackOverflowError.... recursiveCalls = 2262
StackOverflowError.... recursiveCalls = 2243
StackOverflowError.... recursiveCalls = 2278
class RecursionCheck {
    int recursiveCalls;

    void callItself() {
        recursiveCalls++;

        if (recursiveCalls % 1000 == 0) {
            System.out.println("recursiveCalls = " + recursiveCalls);
        }

        try {
            callItself();
        }
        catch (StackOverflowError r) {
            System.out.println("StackOverflowError.... recursiveCalls = " + recursiveCalls);
        }
    }
}

public class RecursionExperiment {
    public static void main(String[] args) {
        new Thread(() -> new RecursionCheck().callItself()).start();
    }
}
Iaroslav Baranov
  • 1,100
  • 9
  • 17
  • Just taking a guess: the JVM uses a system thread, so these are real stack numbers. The JVM also optimizes your code over time (for micro benchmarks, I've noticed that the optimizer has nothing to do *but* continually optimize your code over time), so the exact size of the stack frame is likely to vary depending on exactly what the optimizer did with it last. – markspace Sep 20 '20 at 18:08

0 Answers0