[Logo]
Forums Register Login
Garbage collection




When // doStuff is reached, how many objects are eligible for GC?

A. 0
B. 1
C. 2
D. Compilation fails.
E. It is not possible to know.
F. An exception is thrown at runtime.

I got the answer b.Please correct me i am wrong


Answer b (2 objects). seems to be the right answer.

Line 10 nulls c2 created on line 9 ( that's 1 object )
Line 11 nulls c1 created on line 8 ( that's 2 objects )
Line 10 assigns null to c3 which was never instantiated,
so.. ( that's still 2 objects, right? )
OOPS!

b was not 2 objects.
c was 2 objects... I think 2 objects are available for GC... so answer c.
this thread.


Here two objects are eligible for garbage collection.
But which are those two?
At line no 10, no abject is created and null is assign to c3.
At line no 11, one object is eligible for gargbage collection (The one which was created at line 8).
Since CardBoard has one instance variable Short story, which is not reachable, this object also is eligible for garbage collection.
Thus CardBoard and one Short object are eligible for garbage collection.
Hey,
Here After line 10 ,the CardBoard objects at line 9 becomes eligible for Garbage Collection since c2 is made to point to null while calling in method go().
At line 11 ,the CardBoard object present in line 8 becomes eligible.
Hence two cardboard objects becomes eligible for Garbage Collection.

I dont understand why Short object story becomes elligble for Garbage collection.
I think only object referenced by c1 will be eligible for garbage collection.

Since parameters are passed by value, c2 in main will not be made null, so this object is not available for garbage collection.

No object was created and referenced by c3, it was just initialized to null.

So only 1 object should be eligible for garbage collection.
 

Originally posted by Rajesh Kadle:
I think only object referenced by c1 will be eligible for garbage collection.

Since parameters are passed by value, c2 in main will not be made null, so this object is not available for garbage collection.

No object was created and referenced by c3, it was just initialized to null.

So only 1 object should be eligible for garbage collection.



Correct.
You can always modify the code to get an idea what is happening. But realize that System.gc may not always do what you want it to.
I'm not satisfied.
This is the same example, sited in the K & B, SCJP 5 book (Page 266).
It says..
Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible.
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards


This thread has been viewed 595 times.

All times above are in ranch (not your local) time.
The current ranch time is
Jun 25, 2018 00:16:58.