1

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
i'm a girl
  • 308
  • 3
  • 11
  • 2
    Wouldn't it be better to change the algorithm to an iterative one? – JavaMan Nov 13 '20 at 23:33
  • 1
    The stack is set at JVM startup, so unless that "elsewhere" provides a way to adjust it then no. – Kayaman Nov 13 '20 at 23:33
  • @JavaMan yeah thats probably what ill do but there is so much stuff I need to change that I was trying to avoid it – i'm a girl Nov 13 '20 at 23:42
  • Or you can store the current state in a `Stack` instance. Of course you could not use recursion in this case and would have to manually maintain the stack operations. – Robert Nov 13 '20 at 23:44
  • 3
    You can [construct a new thread with an explicit stack size](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)). However, whether it is respected or how much stack size you need, is implementation specific. The latter may even change in the same runtime. See [Why is the max recursion depth I can reach non-deterministic?](https://stackoverflow.com/q/27043922/2711488) – Holger Nov 14 '20 at 10:38
  • Maybe I'm missing something, but why don't you switch to an `ArrayDeque` or something similar? It even shares the same method signatures as `Stack`. – chn4 Nov 14 '20 at 17:51

1 Answers1

0

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)

i'm a girl
  • 308
  • 3
  • 11