-1

Whenever I try to solve some problems, through recursion in Java, I get StackOverflow. I have checked my implementation but they are right. And when the same code is written in C++ with the same logic, it runs perfectly fine.

Is there a specific recursive stack size in Java and C++??

If yes, how does that work and what is the limit?

1 Answers1

1

The stack size is actually the stack size as used by the Java VM. As such it is an implementation detail. How much stack space is available can often be controlled. For the standard Java VM that's the -Xss setting, where X basically means that it is specific to that particular Java version (i.e. it may be retained, but no assurance is given). See the Java documentation for more details, as you can see it is still present in Java 19.

Note that this will increase the stack size for each thread, so use with some care. You can e.g. try and increase it to 4 MB by performing java -Xss4M .... Usually applications such as Tomcat allow you to define these kind of settings through a configuration file or something similar.

I'm myself not a big fan of deeply recursive functions, and prefer to use other methodologies (looping, lambda's etc.) to achieve the same. Stack ops are expensive and the issue of running out of memory remains very real as it is dependent on the input rather than the application code itself.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263