Stack overflows from deep recursion in Java?

2019-01-03 04:52发布

After some experience with functional languages, I'm starting to use recursion more in Java - But the language seems to have a relatively shallow call stack of about 1000.

Is there a way to make the call stack bigger? Like can I make functions that are millions of calls deep, like in Erlang?

I'm noticing this more and more when I do Project Euler problems.

Thanks.

10条回答
再贱就再见
2楼-- · 2019-01-03 05:13
public static <A, B> Promise<B> foldRight(final Strategy<Unit> s,
                                          final F<A, F<B, B>> f,
                                          final B b,
                                          final List<A> as)
{
    return as.isEmpty() ? promise(s, P.p(b))
    : liftM2(f).f(promise(s, P.p(as.head())))
      .f(join(s, new F<List<A>, P1<Promise<B>>>()
        {
             public Promise<B> f(List<A> l)
             {
                 return foldRight(s, f, b, l);
             }
         }.f(as.tail())));
}
查看更多
放我归山
3楼-- · 2019-01-03 05:14

You can set this on the commandline:

java -Xss8M class

查看更多
混吃等死
4楼-- · 2019-01-03 05:15

in eclipse if you are using, set -xss2m as vm arguments.

or

-xss2m directly on commandline.

java -xss2m classname
查看更多
对你真心纯属浪费
5楼-- · 2019-01-03 05:20

Clojure, which runs on the Java VM, would very much like to implement tail call optimization, but it can't due to a restriction in the JVM bytecode (I don't know the details). As a consequence, it can only help itself with a special "recur" form, which implements a few basic features you'd expect from proper tail recursion.

Anyway, this means that the JVM currently cannot support tail call optimization. I would strongly suggest not to use recursion as a general looping construct on the JVM. My personal view is that Java is not a sufficiently high level language.

查看更多
登录 后发表回答