Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I get a StackOverFlowException on this code because my JVM doesn't support tail call optimizaion, right? [duplicate]

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?

like image 786
Eddy Avatar asked Dec 13 '10 13:12

Eddy


People also ask

Does Java 11 have tail call optimization?

Java doesn't have tail call optimization for the same reason most imperative languages don't have it. Imperative loops are the preferred style of the language, and the programmer can replace tail recursion with imperative loops.

What is tail optimization Java?

Tail recursion is a compile-level optimization that is aimed to avoid stack overflow when calling a recursive method.

What is tail recursive in Java?

Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. For example the following C++ function print() is tail recursive. Java. Python3.

What is tail optimization?

Tail call optimization is the specific use of tail calls in a function or subroutine that eliminate the need for additional stack frames. Tail call optimization can be part of efficient programming and the use of the values that subroutines return to a program to achieve more agile results or use fewer resources.


1 Answers

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:

  • "Tail calls in the VM" by John Rose @ Oracle.
  • Bug 4726340 - RFE: Tail Call Optimization
like image 149
Stephen C Avatar answered Nov 15 '22 08:11

Stephen C