Why does stack overflow not occur?

I am currently learning Java and as part of my training, I tried to intentionally cause a stack overflow to see what it would do.

I did some border testing, and interestingly, I found that if I execute the following code, it will sporadically cause an error. Sometimes it will work without any problems.

public class SO { public static void main(String[] args) { ohno(0); } public static void ohno(int a) { System.out.println(a); if (a != 11413) ohno(a+1); } } 

My questions are as follows:

  • What could lead to the fact that the size of my stack may vary depending on the execution of this very simple example?
  • Stack overflows these days due to poor code construction (i.e. infinite recursion, overly large primitives, etc.) or are there real world scripts where the stack is still a technical limitation?
  • This may seem obvious, but .. does the physical memory of the system also increase the size of the stack?
+6
source share
3 answers

The limited stack size is a function of how much memory you allocate for the JVM.

Systems with limited resources have less memory that can be allocated, so there are absolutely real scenarios where the stack size is a limitation, and there are times when you should use iterative solutions for naturally recursive problems as a result.

Increasing the physical memory of a system is only relevant if you allow this memory to be allocated by the JVM, otherwise you will get the default settings for this platform.

+3
source

The likelihood of a StackOverflowException being raised depends on how much memory you have allocated using the XmxM / G options for maximum memory and XmxS / G at least.

Stack overflows can occur in any situation, if there is a dead loop, or it has the potential to get it through its own loop with a large amount (which depletes a lot of memories) of the data.

+1
source

Many compilers detect tail recursive calls and reuse the same stack stack for this call, thereby preventing the growth of such stacks. A tail recursive call is one where the recursive call is the last statement in a method or function. This optimization allows you to use tail recursion without worrying about stack overflows.

If you want to cause an overflow, try adding code after a recursive call to prevent optimization. You may have to play a little with it - good compilers are cunning and can undermine simple attempts.

0
source

Source: https://habr.com/ru/post/972960/


All Articles