0

Can You please explain this answer..? As I expected answer C

 Given:
 11. class Snoochy {
 12. Boochy booch;
13. public Snoochy() { booch = new Boochy(this); }
14. }
15.
16. class Boochy {
17. Snoochy snooch;
18. public Boochy(Snoochy s) { snooch = s; }
19. }
And the statements:
21. public static void main(String[] args) {
22. Snoochy snoog = new Snoochy();
23. snoog = null;
24. // more code here
25. }

Which statement is true about the objects referenced by snoog, snooch, and booch immediately after line 23 executes?

   A. None of these objects are eligible for garbage collection.
   B. Only the object referenced by booch is eligible for garbage collection.
   C. Only the object referenced by snoog is eligible for garbage collection.
   D. Only the object referenced by snooch is eligible for garbage collection.
   E. The objects referenced by snooch and booch are eligible for garbage collection.

Answer: E
Tez
  • 83
  • 1
  • 9
  • Smells like coding competition :) – Suresh Atta Apr 25 '13 at 06:34
  • 3
    What is stopping `booch` being collected? I would expect E. – Peter Lawrey Apr 25 '13 at 06:35
  • You say the answer is `C`, but the question you posted says the answer is `E`. – Rahul Apr 25 '13 at 06:36
  • Possibly :http://certificationpath.com/view/sun-certified-programmer-for-the-java-2-platform-standard-edition-50/content/given-the-code11-class-snoochy-12-boochy-booch13-public-snoochy--booch-q19449 – AllTooSir Apr 25 '13 at 06:38
  • BTW if you believe that `booch` cannot be collected, this would mean that `snoog` cannot be collected either as `booch` has a reference to it. – Peter Lawrey Apr 25 '13 at 07:06
  • The general rule is: if you can't access it (including indirectly) from `main`, a static field, or a Thread/Runnable/Callable/etc that's running, then it's eligible for GC. At line 24, you can't access any instances, so everything's eligible for GC. (Interned strings are an edge case that we can ignore for now...) – yshavit Apr 25 '13 at 07:52
  • You are right..I thought the instance variables of an object which is eligible for gc , are not eligible for gc if they are not null – Tez Apr 25 '13 at 10:29

2 Answers2

3

The two classes reference each other. So, when snoog is created, you also get a booch and a snooch. when you set snoog = null; , booch and snooch are eligible for GC.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
0

After line 23 there is no reference left pointing to the Snoochy instance created in line 22. => this instance can be garbage collected. But this instance contains a reference to a Boochy (see line 13) to which no other reference existas. =: this can be garbagecollected too.

MrSmith42
  • 9,961
  • 6
  • 38
  • 49