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?
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.
Tail recursion is a compile-level optimization that is aimed to avoid stack overflow when calling a recursive method.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With