Girish K Gupta wrote:Is it possible to set the maximum number of call stack depth in Java?
I found that the non standard JVM argument (-Xss) is used to specify the maximum memory of a particular stack BUT not the number of frames in the stack.
Can anyone throw some light or provide any pointers?
Welcome to CodeRanch!
I'm not sure whether this is generically possible, but if you are concerned with recursion, then getStackTraceDepth method of Throwable class might be helpful. It won't control anything, but it would return the depth, based on which, you can modify the behavior of the method.
I don't think there is such a thing as a maximum stack depth. There is a maximum amount of memory that can be used for the stack. This can be tweaked using -Xss followed by the size; for example, -Xss64M will have a stack size of 64MB. Each time a method is called, its variables are put on the stack until this 64MB is full.
As an example, run the following using both javaTest and java -Xss64M Test, and see the difference:
@Anayonkar, I could not find any method, getStackTraceDepth, in Throwable class. Checked in Java6 specifications. Please let me know if I am missing anything.
@Winston, I completely understand your view point but I have worked on a customized JVM for embedded devices where a maximum of 128 call depth was allowed. For standard Java this is not a constraint at all. I asked this question more from understanding point of view.
@Rob, I tried your test application and learnt what I wanted. Thanks again !
Girish K Gupta wrote: I tried it but the length of arrays returned getStackTrace() method is always 1024 for my system while value of depth variable is around 12000 in different executions.
This is where those JVM arguments come into picture (where you can change JVM's memory size etc.)
However, in my opinion, even 1024 is much more. As some of the replies mention, increasing the JVM size is not the solution.
The first question I would ask myself - what kind of operation requires a method calling itself 12000(or 1024) times?
The second question - Can it be done by using a loop instead of recursion?
In general, recursion is very helpful - provided its done correctly. Once it gets out of control, then debugging is much difficult.