Java递归堆栈大小

huangapple go评论63阅读模式
英文:

Java Recursive Stack Size

问题

每当我尝试通过Java中的递归来解决一些问题时,我会遇到栈溢出的问题。我已经检查了我的实现,但它们是正确的。而当相同的代码以相同逻辑写在**C++**中时,它可以正常运行。

Java和C++中是否有特定的递归栈大小?

如果有,它们是如何工作的,以及限制是多少?

英文:

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

得分: 1

栈大小实际上是Java虚拟机使用的栈大小。因此,这是一个实现细节。可以经常控制可用的栈空间。对于标准的Java虚拟机,可以使用-Xss设置来控制栈大小,其中X基本上表示它是特定于该特定Java版本的(即可能会保留,但不提供保证)。有关更多详细信息,请参阅Java文档,正如您所见,它在Java 19中仍然存在。

请注意,这将增加每个线程的栈大小,因此请谨慎使用。例如,您可以尝试将其增加到4MB,方法是执行java -Xss4M ...。通常,应用程序(如Tomcat)允许您通过配置文件或类似的方式来定义这些设置。

我个人不太喜欢深度递归函数,更喜欢使用其他方法(循环、Lambda等)来实现相同的功能。栈操作很昂贵,内存耗尽的问题仍然非常真实,因为它取决于输入而不是应用程序代码本身。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月19日 02:29:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75495495.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定