Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage Collection in Java with Recursive Function

I know that objects become unreachable and marked for garbage collection in every iteration of a regular loop. What about recursive calls? Something like:

public void doWork() {

    Object a = new Object();

    ....some work with a...

    this.sleep(60000);
    doWork();


  }

Is the object (i.e. 'a') in the first recursion marked for garbage collection once the second recursion begins or does it need to be explicitly marked null since the outer function never finishes because of the recursion.

like image 657
esen Avatar asked Jan 05 '15 14:01

esen


2 Answers

During each recursive call the local variables(here the reference "a") are pushed onto the stack. Local variable are GC roots. During the second recursive call the new reference is pushed onto the stack. However, the first reference is still there and thus the object is still reachable and thus can't be garbage collected.

Thus if you want the first created object to be marked for garbage collection(while the function hasn't yet finished) you should explicitly set "a" to null.

Here is a useful link to understand GC: http://javabook.compuware.com/content/memory/how-garbage-collection-works.aspx

like image 94
javaHunter Avatar answered Sep 29 '22 01:09

javaHunter


I have found that local variables referencing objects are garbage collected if they are no longer needed. However, this does not apply when debugging. I guess the debugger keeps a reference to it, but in regular execution there is no need for it.

Try executing the following code, and see what happens.

Object o1 = new Object();
System.out.println(o1);
WeakReference<Object> wr = new WeakReference<Object>(o1);
System.gc();
System.out.println(wr.get());

My output (without debugger):

java.lang.Object@20662d1
null

My output (with debugger):

java.lang.Object@206b4fc
java.lang.Object@206b4fc

It would therefore appear that the earlier references are garbage collected, even when the local method is still on the stack.

like image 34
Joseph K. Strauss Avatar answered Sep 29 '22 02:09

Joseph K. Strauss