Java Programming - Garbage Collections - Discussion

Discussion Forum : Garbage Collections - General Questions (Q.No. 1)
1.
void start() {  
    A a = new A(); 
    B b = new B(); 
    a.s(b);  
    b = null; /* Line 5 */
    a = null;  /* Line 6 */
    System.out.println("start completed"); /* Line 7 */
} 
When is the B object, created in line 3, eligible for garbage collection?
after line 5
after line 6
after line 7
There is no way to be absolutely certain.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
59 comments Page 5 of 6.

Utkarsh said:   5 years ago
I believe answer should be B.

Clearly we still have a.s referencing B object (new B()) and only after a is set to null the whole chain would break.

Winston said:   1 decade ago
It's definitely D. I even profiled the example and saw that object B still stays in memory ONLY IF a.s(b); method stores b into a static variable.

Ankur said:   1 decade ago
That is totally depend on the jvm implementation and algorithm that provide how and which time to rin gc() method we don't need to worry about it.

Nikhil Nambiar said:   9 years ago
Option D is right because there is no assurance of garbage collector activity. And we cannot even predict the implicit call to finalize method.

Mit said:   1 decade ago
Option A is correct Even if we assign that object reference to some other B = null removes from B. Therefore b will be eligible after line 5.

TheExodu5 said:   9 years ago
@Mayank.

The reference was passed to A.s. That reference may still exist, and the original object can still be accessed.

The answer is D.

Xinu said:   9 years ago
If the 'b' is assigned, by some different reference, in side the method s(b), then, 'b' will not come across garbage collection.

Chandan Kumar said:   1 decade ago
The garbage collector does not indicate when it is going to be called. Hence you can never be certain when GC will be called.

Achleshwar said:   1 decade ago
Its 'A' because in 3rd line we are declare the function and in 5th line we assign the value of the function.

Bineeth said:   1 decade ago
Actually, Garbage Collection in Java is Unpredictable. So we can say both options A and D are correct.


Post your comments here:

Your comments will be displayed after verification.