Search code examples
javamemorystack-overflow

Why doesn't a stack overflow always occur?


I'm currently studying Java and, as a part of my learning, I attempted to intentionally induce a stack overflow to see what it would do.

I did some boundary testing and, interestingly, I discovered that if I execute the following code it will only sporadically cause an error. Sometimes it will run 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 might be causing my stack size to vary between executions of this very simple example?
  • These days, does a stack overflow always occur due to poor code design (i.e. infinite recursion, excessively large primitives, etc.) or are there real world scenarios where the stack is still a technical limitation?
  • This one may seem obvious but.. does increasing the physical memory of a system also increase the size of the stack?

Solution

  • Limited stack size is a function of how much memory you allocate to the JVM.

    Resource-constrained systems have less memory that can be allocated, so absolutely there are real-world scenarios where stack size is a limitation, and there are times where you have to use iterative solutions to naturally-recursive problems as a result.

    Increasing the physical memory of a system only matters if you allow that memory to be allocated by the JVM, otherwise you'll get the defaults of that platform.