Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

java - Garbage collection mock for the OCPJP exam

Four objects are eligible for garbage collection when i3 = null; is executed in the class shown below. I've added comments to explain how I got this answer. Is my reasoning correct?

public class Icelandic extends Horse{
    public void makeNoise(){
        System.out.println("vinny");
    }

    public static void main(String args[]){
        /**
         * 2 objects created
         */
        Icelandic i1 = new Icelandic();

        /**
         * 2 objects created
         */
        Icelandic i2 = new Icelandic();

        /**
         * 2 objects created
         */
        Icelandic i3 = new Icelandic();

        /**
         * i3 is now pointing at i1, original Icelandic() referred to by i3 now
             * has no reference -  2 objects now have no reference
         */
        i3 = i1;

        /**
         * i3 is now pointing at i1, original Icelandic() referred to by i1 now
             * has no reference -  2 objects now have no reference
         */
        i1 = i2;

        /**
         * Total of six objects created, 4 objects no longer have a reference so 4
             * can be garbage collected.
         * 
         * Setting to null below doesn't make any difference to garbage collector
             * as objects now do not have a reference
         */
        i2 = null;
        i3 = null;
    }
}

interface Animal {
    void makeNoise();
}

class Horse implements Animal{
    Long weight = 1200L;

    public void makeNoise() {
        System.out.println("whinny");
    }    
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

These are steps of your program:

    Icelandic i1 = new Icelandic();
    Icelandic i2 = new Icelandic();
    Icelandic i3 = new Icelandic();

enter image description here

    i3 = i1;
    i1 = i2;

enter image description here

    i2 = null;
    i3 = null;

enter image description here

So the last diagram concludes that only 2 objects are ready for garbage collection. I hope I am clear. You can see object names as references to the objects.

EDIT:

As said by BalusC, Long weight = 1200L is also object. So 2 more objects each for i1 and i3 are eligible or garbage collections. So in all 4 objects are eligible or garbage collection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...