File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Regular inner classes & garbage collection" Watch "Regular inner classes & garbage collection" New topic

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

Joined: Sep 28, 2004
Posts: 20538

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?


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

Joined: Oct 27, 2005
Posts: 20279

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.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Regular inner classes & garbage collection
jQuery in Action, 3rd edition