How to extend stack size without access to JVM settings?

那年仲夏 提交于 2021-01-01 08:16:24

问题


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?

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.


回答1:


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)

Example:

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)



来源:https://stackoverflow.com/questions/64829317/how-to-extend-stack-size-without-access-to-jvm-settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!