| Start |
|---|
| Deep recursion is problematic in Java Consider the following naive method for adding two positive numbers using recursion: This is algorithmically correct, but it has a major problem. If you call In a typical functional programming language (and many other languages) the compiler optimizes tail recursion (opens new window). The compiler would notice that the call to However, current generation Java compilers do not perform tail call elimination. (This is not a simple oversight. There are substantial technical reasons for this; see below.) Instead, each recursive call of The problem is that the size of Java thread stack is fixed when the thread is created. (This includes the "main" thread in a single-threaded program.) If too many stack frames are allocated the stack will overflow. The JVM will detect this and throw a One approach to dealing with this is to simply use a bigger stack. There are JVM options that control the default size of a stack, and you can also specify the stack size as a The real solution is to identify recursive algorithms where deep recursion is likely, and manually perform the tail-call optimization at the source code level. For example, our (Obviously, there are better ways to add two integers. The above is simply to illustrate the effect of manual tail-call elimination.) Why tail-call elimination is not implemented in Java (yet)There are a number of reasons why adding tail call elimination to Java is not easy. For example:
As John Rose explains in "Tail calls in the VM" (opens new window): "The effects of removing the caller’s stack frame are visible to some APIs, notably access control checks and stack tracing. It is as if the caller’s caller had directly called the callee. Any privileges possessed by the caller are discarded after control is transferred to the callee. However, the linkage and accessibility of the callee method are computed before the transfer of control, and take into account the tail-calling caller." In other words, tail-call elimination could cause an access control method to mistakenly think that a security sensitive API was was being called by trusted code. |
| The basic idea of recursion What is recursion: In general, recursion is when a function invokes itself, either directly or indirectly. For example: Conditions for applying recursion to a problem: There are two preconditions for using recursive functions to solving a specific problem: In Java there is a third precondition: it should not be necessary to recurse too deeply to solve the problem; see Deep recursion is problematic in Java (opens new window) Example The following function calculates factorials using recursion. Notice how the method This is not a practical way of computing factorials in Java, since it does not take account of integer overflow, or call stack overflow (i.e. |
| Types of Recursion Recursion can be categorized as either Head Recursion or Tail Recursion, depending on where the recursive method call is placed. In head recursion, the recursive call, when it happens, comes before other processing in the function (think of it happening at the top, or head, of the function). In tail recursion, it’s the opposite—the processing occurs before the recursive call. Choosing between the two recursive styles may seem arbitrary, but the choice can make all the difference. A function with a path with a single recursive call at the beginning of the path uses what is called head recursion. The factorial function of a previous exhibit uses head recursion. The first thing it does once it determines that recursion is needed is to call itself with the decremented parameter. A function with a single recursive call at the end of a path is using tail recursion. If the recursive call occurs at the end of a method, it is called a If the recursive call occurs at the Reference: The difference between head & tail recursion (opens new window) |
| Computing the Nth Fibonacci Number The following method computes the Nth Fibonacci number using recursion. The method implements a base case (n <= 2) and a recursive case (n>2). This illustrates the use of recursion to compute a recursive relation. However, while this example is illustrative, it is also inefficient: each single instance of the method will call the function itself twice, leading to an exponential growth in the number of times the function is called as N increases. The above function is O(2N), but an equivalent iterative solution has complexity O(N). In addition, there is a "closed form" expression that can be evaluated in O(N) floating-point multiplications. |
| Computing the Nth power of a number The following method computes the value of This illustrates the principles mentioned above: the recursive method implements a base case (two cases, n = 0 and n = 1) that terminates the recursion, and a recursive case that calls the method again. This method is O(N) and can be reduced to a simple loop using tail-call optimization. |
| Traversing a Tree data structure with recursion Consider the Node class having 3 members data, left child pointer and right child pointer like below. We can traverse the tree constructed by connecting multiple Node class's object like below, the traversal is called in-order traversal of tree. As demonstrated above, using recursion we can traverse the tree data structure without using any other data structure which is not possible with the iterative approach. |
| StackOverflowError & recursion to loop If a recursive call goes "too deep", this results in a ExampleCalling this method with large parameters (e.g. WorkaroundA recursion can be converted to a loop by storing the data for each recursive call in a data structure. This data structure can be stored on the heap rather than on the thread stack. In general the data required to restore the state of a method invocation can be stored in a stack and a while loop can be used to "simulate" the recursive calls. Data that may be required include:
ExampleThe following class allows recursive of a tree structure printing up to a specified depth. e.g. Prints This could be converted to the following loop: Note: This is just an example of the general approach. Often you can come up with a much better way to represent a frame and/or store the frame data. |
| Computing the sum of integers from 1 to N The following method computes the sum of integers from 0 to N using recursion. This method is O(N) and can be reduced to a simple loop using tail-call optimization. In fact there is a closed form expression that computes the sum in |
| Reverse a string using Recursion Below is a recursive code to reverse a string RemarksDesigning a Recursive MethodWhen designing a recursive method keep in mind that you need: OutputIn this example you compute the n-th factorial number. The first factorials are: 0! = 1 1! = 1 2! = 1 x 2 = 2 3! = 1 x 2 x 3 = 6 4! = 1 x 2 x 3 x 4 = 24 ... Java and Tail-call eliminationCurrent Java compilers (up to and including Java 9) do not perform tail-call elimination. This can impact the performance of recursive algorithms, and if the recursion is deep enough, it can lead to |
Read Article
https://develop.horje.com/learn/1434/reference