my dog learned polymorphism*
The moose likes Java in General and the fly likes Regular inner classes & garbage collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Regular inner classes & garbage collection" Watch "Regular inner classes & garbage collection" New topic
Author

Regular inner classes & garbage collection

Dariusz Kordonski
Ranch Hand

Joined: Jul 11, 2008
Posts: 49
What happens, if an instance of an outer class becomes gc-eligible but there are instances of its inner class (in relation with this particular outer class instance) that are still referenced from stack or other objects? Is it possible at all?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18914
    
  40

Think about it. To be GC eligible, an object can't be reachable. How do you propose that an object be GC eligible, if it is still reachable from an inner class object?

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Dariusz Kordonski
Ranch Hand

Joined: Jul 11, 2008
Posts: 49
I think the problem is that there are a lot of sources that define 'being reachable' as 'there is somewhere a reference variable that points to this object'. And this is the way I always thought of it. And since there may be no direct reference variable pointing to outer class within the inner class, according to such definition it could be possible for an outer class instance to be gc-eligible. But, of course, if we think of being reachable in general sense, it is always possible to reach outer class with 'OuterClass.this' from within inner class... are there any more cases when 'object is not reachable != 'there is no reference variable pointing to it' ?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19725
    
  20

An instance of an inner class has a reference to the outer class (available through OuterClass.this). So if the instance of the outer class is gc-eligible, then the inner class instance is gc-eligible by definition. If the inner class instance is not gc-eligible then neither is the outer class instance.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Regular inner classes & garbage collection