Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>After digging around for a while, I can't say that I find the answer, but I think it's quite close now.</p> <p>First, we need to know when a <code>StackOverflowError</code> will be thrown. In fact, the stack for a java thread stores frames, which containing all the data needed for invoking a method and resume. According to <a href="http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.12.4.5" rel="nofollow">Java Language Specifications for JAVA 6</a>, when invoking a method,</p> <blockquote> <p>If there is not sufficient memory available to create such an activation frame, an StackOverflowError is thrown.</p> </blockquote> <p>Second, we should make it clear what is "<em>there is not sufficient memory available to create such an activation frame</em>". According to <a href="http://docs.oracle.com/javase/specs/jvms/se5.0/html/Overview.doc.html#6654" rel="nofollow">Java Virtual Machine Specifications for JAVA 6</a>,</p> <blockquote> <p>frames may be heap allocated.</p> </blockquote> <p>So, when a frame is created, there should be enough heap space to create a stack frame and enough stack space to store the new reference which point to the new stack frame if the frame is heap allocated.</p> <p>Now let's go back to the question. From the above, we can know that when a method is execute, it may just costs the same amount of stack space. And invoking <code>System.out.println</code> (may) needs 5 level of method invocation, so 5 frames need to be created. Then when <code>StackOverflowError</code> is thrown out, it has to go back 5 times to get enough stack space to store 5 frames' references. Hence 4 is print out. Why not 5? Because you use <code>cnt++</code>. Change it to <code>++cnt</code>, and then you will get 5.</p> <p>And you will notice that when the size of stack go to a high level, you will get 50 sometimes. That is because the amount of available heap space need to be taken into consideration then. When the stack's size is too large, maybe heap space will run out before stack. And (maybe) the actual size of stack frames of <code>System.out.println</code> is about 51 times of <code>main</code>, therefore it goes back 51 times and print 50.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload