Java 5 garbage collection

This code snippet is from the book. The question is

  • how many objects have been created
  • how many objects fit gc when the line is reached // does stuff.

The answers, according to the book, are 5 and 2. Here's 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 consider the int [] dz object to be an additional object every time you instantiate Dozens?

Likewise, when you reach // do stuff, when calculating the number of eligible gc objects for each Dozens object, do you also count the int [] dz object it contains?

I didn't count int [] dz objects and came up with answers 5 and 3.

Can someone please explain what I might be doing wrong?

Thank.

+3


source to share


1 answer


I wrote the annotated code below with comments to highlight where links are created or lost.

When calculating distributions, you must specify the distribution of the array stored in the dz field. My suspicion is that you have counted the assignment of object references to da [0] and da [1] as distributions. Because they copy the link rather than create a new object; they only affect when objects can become GCable and 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 up the totals gives 1 + 2 + 2 = 5 distributions. -2 at the end concludes that 2 objects have become available to GC

+4


source







All Articles