Is the object (i.e. 'a') in the first recursion marked for the garbage collection after the start of the second recursion or should it be explicitly marked as null, since the outer function never ends due to recursion.
Answer: it depends on the platform.
The variable a is still in scope until the doWork() declaration instance is returned. On the other hand, it is obvious to us that by the time that the variable a cannot affect the calculation as soon as we reach the recursive call, and (theoretically), this means that the GC no longer needs to consider it for purposes of determining reachability.
So it boils down to whether the JVM is smart enough to realize that a doesn't matter anymore. It depends on the platform. And as another answer notes, working with a debugger application can change that.
Another answer mentions tail call optimization. Of course, if the JVM performed this optimization, then the "old" a will conceptually be replaced by the "new" in the optimized "call". However, none of JSM HotSpot (at least prior to Java 8) implements tail call optimization, since optimization will interfere with Java code, which relies on the ability to count stack frames; for example, a security code.
However, if this particular code was a significant storage leak, then it is likely to be controversial because (in the absence of tail call optimization) the code will most likely give you a StackOverflowError before it fills the heap.
source share