Why does this method print 4?

前端 未结 7 1649
抹茶落季
抹茶落季 2020-12-12 13:18

I was wondering what happens when you try to catch an StackOverflowError and came up with the following method:

class RandomNumberGenerator {

    static int         


        
7条回答
  •  渐次进展
    2020-12-12 14:04

    The behavior is dependent upon the stack size (which can be manually set using Xss. The stack size is architecture specific. From JDK 7 source code:

    // Default stack size on Windows is determined by the executable (java.exe
    // has a default value of 320K/1MB [32bit/64bit]). Depending on Windows version, changing
    // ThreadStackSize to non-zero may have significant impact on memory usage.
    // See comments in os_windows.cpp.

    So when the StackOverflowError is thrown, the error is caught in catch block. Here println() is another stack call which throws exception again. This gets repeated.

    How many times it repeates? - Well it depends on when JVM thinks it is no longer stackoverflow. And that depends on the stack size of each function call (difficult to find) and the Xss. As mentioned above default total size and size of each function call (depends on memory page size etc) is platform specific. Hence different behavior.

    Calling the java call with -Xss 4M gives me 41. Hence the correlataion.

提交回复
热议问题