5

I get a StackOverflowException on this Java method:

private static final Integer[] populate(final Integer[] array, final int length, final int current) {

    if (current == length) {
        return array;
    } else {
        array[current] = TR.random.nextInt();
        System.out.println(array[current]);
        return populate(array, length, current + 1);
    }
}

I'm playing with tail call recursion so I guess this is what happens when the JVM doesn't short circuit the stack right?

Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
Eddy
  • 1,662
  • 2
  • 21
  • 36

4 Answers4

7

No JVM that I'm aware of supports tail call optimization. This is not an oversight. Apparently this optimization has significant consequences for Java reflection and Java security managers.

References:

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
3

Yes, Tail Call Optimization is not currently supported by the JVM because of the security model and the need to always have a stack trace available, this example could easily be rewritten using iteration though.

Neal Donnan
  • 1,733
  • 1
  • 13
  • 18
  • Hi, of course it can be easily expressed with a for loop... it's an exercise after all ;) – Eddy Dec 13 '10 at 14:22
1

I found a reference of tail recursion in java, therefore I would check this, (later when I've time).

Although it would be extremly ineffiecent for your use case.

stacker
  • 68,052
  • 28
  • 140
  • 210
  • I don't think the document adds much... the reference to tail recursion doesn't mention whether the stack references are optimized away – Eddy Dec 14 '10 at 13:48
1

Plain Java doesn't have tail call optimization, AFAIK. Scala does have a somewhat limited implementation of it: http://fupeg.blogspot.com/2009/04/tail-recursion-in-scala.html

gmw
  • 417
  • 3
  • 15