如何在不访问JVM设置的情况下扩展堆栈大小? [英] How to extend stack size without access to JVM settings?

查看:91
本文介绍了如何在不访问JVM设置的情况下扩展堆栈大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我要提交要在其他地方运行的代码,因此我无权访问JVM设置,因此我无法遵循有关扩展堆栈大小的其他Stack Overflow答案.有什么办法可以从我的Java文件中执行此操作?

I do not have access to the JVM settings since I am submitting code to be run elsewhere, so I can't follow the other Stack Overflow answers about extending stack size. Is there any way to do it from inside my Java file?

我要这样做的原因(不是很重要):
我在具有10 ^ 5个节点的树上使用递归.一般情况是可以的,但是不能保证树的形状.我正在处理一个边缘情况,其中树只是一条长线.我收到一个StackOverflowError,但是如果我可以扩展堆栈大小,我的算法就可以正常运行.尽管我已经通过找到树的质心或使用稀疏矩阵来处理这种情况,但我宁愿将堆栈大小加倍并使用现有代码.

The reason I want to do this (not really important):
I am using recursion on a tree with 10^5 nodes. The average case is ok, but there is no guarantee on the shape of the tree. I am dealing with an edge case where the tree is just one long line. I get a StackOverflowError, but my algorithm would run fine if I could just extend my stack size. I've though about dealing with this case by finding the centroid of the tree or using sparse matrixes, but I would much rather just double my stack size and use my existing code.

推荐答案

要总结这些评论,您可以创建一个新的Thread并指定一个堆栈大小,尽管文档说效果与平台高度相关(适用于我的至少计算机).在此处查看更多信息:

To sum up the comments, you can create a new Thread and specify a stack size, though the docs say that the effects are highly platform dependent (works on my computer at least). See more here: https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/Thread.html#%3Cinit%3E(java.lang.ThreadGroup,java.lang.Runnable,java.lang.String,long)

示例:

public static void main(String[] args)
{
    Thread thread1 = new Thread(null, null, "qwer", 1000000) {
        public void run() {
            System.out.println(countDepth());
        }
    };
    thread1.start();
}
public static int countDepth() {
    try {return 1+countDepth();}
    catch(StackOverflowError err) { return 0; }
}

(更改堆栈大小,您将看到更高的递归深度)

(change the stacksize and you will see much higher recursion depths)

这篇关于如何在不访问JVM设置的情况下扩展堆栈大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆