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
263 views
in Technique[技术] by (71.8m points)

java - Objects eligible for garbage collection

This question was taken from Kathy Sierra SCJP 1.6. How many objects are eligible for garbage collections?

According to Kathy Sierra's answer, it is C. That means two objects are eligible for garbage collection. I have given the explanation of the answer. But why is c3 not eligible for garbage collection (GC)?

class CardBoard {
    Short story = 200;
    CardBoard go(CardBoard cb) {
    cb = null;
    return cb;
}

public static void main(String[] args) {
    CardBoard c1 = new CardBoard();
    CardBoard c2 = new CardBoard();
    CardBoard c3 = c1.go(c2);
    c1 = null;
    // Do stuff
} }

When // Do stuff is reached, how many objects are eligible for GC?

  • A: 0
  • B: 1
  • C: 2
  • D: Compilation fails
  • E: It is not possible to know
  • F: An exception is thrown at runtime

Answer:

  • C is correct. Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible.
  • A, B, D, E, and F are incorrect based on the above. (Objective 7.4)
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Let's break this down line by line:

CardBoard c1 = new CardBoard();

We now have two objects, the CardBoard c1 points at and the Short c1.story. Neither is available for GC as c1 points at the CardBoard and the story variable of the CardBoard points at the Short...

CardBoard c2 = new CardBoard();

Similar to above, we now have four objects, none of which are available for GC.

CardBoard c3 = c1.go(c2);

We invoke the method go on the CardBoard pointed at by c1, passing the value of c2 which is a reference to a CardBoard Object. We null the parameter, but Java is pass by value meaning that the c2 variable itself is unaffected. We then return the nulled parameter. c3 is null, c1 and c2 are unaffected. We still have 4 objects, none of which can be GC'd.

c1 = null;

We null c1. The CardBoard object which c1 previously pointed at now has nothing pointing to it, and it can be GC'd. Because the story variable inside that CardBoard object is the only thing pointing at the Short, and because that CardBoard object is eligible for GC, the Short also becomes eligible for GC. This gives us 4 objects, 2 of which can be GC'd. The objects eligible for GC are the ones formerly referenced by c1 and c1.story.


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

...