问题
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