Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dan's GC question

 
GM Shobha
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Q {
private int id;
public void finalize() {System.out.print(id);}
public Q(int i) {id = i;}
}
class R {
public static void main(String[] args) {
Q q1 = null;
for (int i = 0; i < 10; i++) {
q1 = new Q(i); // 1
}
System.gc(); // 2
}
}

When the processing of line 2 begins how many objects of type Q that were created at line 1 are eligible for garbage collection?
Answer 10 or 9??
 
G Nadeem
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shobha,
line 2 is a part of main method, and q1 is object holding variable declared within main method,(Q q1=null). now total objects created within 'for' loop are 10. right. however only the last object created (when i==9) will be referenced by (and stored in,roughly speaking) q1. object created from i==0 to 1==8 (i.e 9) will be eligible for GC, as we have not been 'saving' them any where.
 
GM Shobha
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nadeem,
Sometime back, question below was discussed in this forum.
public static void main(String args [])
{
for(int i=10;i>0;i--){
{
String s =new String(�Hello�);
}
System.out.println(�world�); // 9
}
How many objects eligible for GC at line no 9 ? & the answer given was 10.
Pl verify how is this problem different from the above.
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shobha
Well there's a bit of difference between the two codes you have supplied. In the former case(the first post) the variable q1 of type Q is declared outside the for loop so is available after the for loop, but in the later case the variable s of String type is declared in the for loop and hence is not available once the for loop is over. So it is eligible once the for loop is over.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic