Recursion Depth - Java

Posted on April 24, 2014


Recently, in a programming competition, I made a big mistake by using recursion for solving one of the problems, as it resulted in 'StackOverflow' error and lost the chance to solve the problem for a larger input dataset. I realized it immediately and implemented a normal solution, but there wasn't much time to provide the solution.

In Java, the JVM stores the method information (Variables, Return Address, etc) and its parameters in the Stack. So, when you use Recursion, they are constantly pushed to the stack memory, until the result of that method is returned. Usually, Stack has limited memory and is much less than the Heapsize.

Below is a Java program, from which you can find the 'Recursion Depth' of the JVM that you are using:

The current 'Recursion Depth' for the JVM on my System is: 9372

The 'Recursion Depth' depends on the present state of the Stack Memory usage, on your JVM. So, it might change, everytime you run it.

References:

1) My own post on StackOverflow site: Basic Java Recursion Method

Blog Categories
Disclaimer
The views expressed on this blog are my personal views and do not reflect the views of my employer or campaigns I am supporting.

All sample code is provided for illustrative purposes only. These examples have not been thoroughly tested under all conditions. The writer therefore, cannot guarantee or imply reliability, serviceability, or function of these programs.

All programs contained herein are provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.