This piece of code is from a book. The question is,
- how many objects are created
- how many objects are eligible for gc when the line // do stuff is reached.
The answers, according to the book, are 5 and 2. Here is the code:
class Dozens {
int[] dz = {1,2,3,4,5,6,7,8,9,10,11,12};
}
public class Eggs{
public static void main(String[] args){
Dozens[] da = new Dozens[3];
da[0] = new Dozens();
Dozens d = new Dozens();
da[1] = d;
d = null;
da[1] = null;
// do stuff
}
}
In answer to the first question, do you also count the int[] dz object as an additional object each time you instantiate Dozens?
Similarly, when you reach // do stuff, in calculating the number of objects eligible for gc, for each Dozens object, do you also count the int[] dz object contained therein?
I did not count the int[] dz objects, and arrived at the answers 5 and 3.
Can someone explain what I might be doing wrong?
Thanks.
1 Answer 1
I have annotated the code below with comments to highlight where references are created or lost.
When counting allocations, one must include the allocation of the array stored in the field dz. My suspicion is that you counted the assignment of object references to da[0] and da[1] as allocations. Since they are copying a reference, and not creating a new object; they only affect when the objects can become GCable and do not create a new object.
class Dozens {
int[] dz = {1,2,3,4,5,6,7,8,9,10,11,12};
}
public class Eggs{
public static void main(String[] args){
Dozens[] da = new Dozens[3]; // +1 object, the array containing 3 nulls
da[0] = new Dozens(); // +2 objects, Dozens and the array in Dozens.dz
Dozens d = new Dozens(); // +2 objects, Dozens and the array in Dozens.dz
da[1] = d; // +0, d now has two refs to it
d = null; // +0, d now has one ref to it
da[1] = null; // -2, d now has no refs to it so both d and its internal array become available for GC
// do stuff
}
}
Summing the totals up gives, 1+2+2=5 allocations. The -2 at the end concludes that 2 objects have become available for GC
mainmethod, and a String object to hold each command line argument (if any).