Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage collection in Inner classes

 
Ram Reddy
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

if code as follows

class OuterClass
{
int i;
void printInstanceVaraibles()
{
System.out.println("I value "+ i);
}
class InnerClass
{
int j;
void printInstanceVariables()
{
System.out.println("J value " + j);
}
}
}

class Main
{
public static void main(String args[])
{
OuterClass outerClass = new OuterClass();
InnerClass innerClass = outerClass.new InnerClass();
outerClass = null;
//GC
}
}

AT //GC howmany objects are eligible for Garbage Collection?
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the answer is zero, because the innerclass holds a reference to the outerclass.
 
Srinivas Kumar
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can anybody explain? it is really a good question.
 
Sourin K. Sen
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See the answer to this question would seem to be pretty simple if you can understand one basic thing :

inner class's object cannot exist without an instance of the outer class (except for static inner classes which aren't inner classes anyways).

In this case, since inner class has got a reference which is alive, it also means that the instance of outer class is stored safely in inner (we might say as such) because the inner class may need to access the instance members of the outer class & for that it should have a reference to the outer class's object.

Now since the inner class IS referring to the outer class implicitly, it means that there is a reference for the outer class (which we cannot access by the way) & hence no question of the outer class's object being garbage collected.

Note "rami reddy marri" :
the statement
InnerClass innerClass = outerClass.new InnerClass();
is invalid.

Please change it to :
OuterClass.InnerClass innerClass = outerClass.new InnerClass();
[ March 23, 2007: Message edited by: Sourin K. Sen ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic