简体   繁体   中英

Is this the only variable eligible for garbage collection?

I have a question on eligibility of garbage collection for this piece of code.

public static void main(String[] args) {
    Object a = new Object();
    Object b = new Object();
    Object c = new Object();
    a = b;
    b = c;
    c = null;
}

I've read through a couple examples of Java garbage collection and I think I'm getting the hang of it. So what I was thinking is that after the line c = null; only c will be eligible for garbage collection because it's the only object that has discarded all references to it. Am I right here?

Thanks!

In Java, variables are not eligible for garbage collection; objects are. Variables hold references to objects but are not the objects themselves.

Let's look at your example with some sample object IDs (the internal identifiers the JVM uses to keep track of them, and not ordinarily visible):

Object a = new Object(); // id=1
Object b = new Object(); // id=2
Object c = new Object(); // id=3

You now have objects 1, 2, and 3, each referenced from a single variable: a:1, b:2, c:3 . When you copy those references between variables, here's what the state looks like:

a = b;    // a:2, b:2, c:3
b = c;    // a:2, b:3, c:3
c = null; // a:2, b:3, c:null

After a = b , you've lost all references to object 1, which was originally in a , and so it immediately becomes eligible for garbage collection. Objects 2 and 3 are still reachable until the end of the block, where all of the variables fall out of scope together.

Only a's object will be elligible for garbage collection.Take a piece of paper and draw it, and you will know.

在此处输入图片说明

As I read from the book OCA Java SE 7

An object is marked as eligible to be garbage collected when it can no longer be accessed, which can happen when the object goes out of scope. It can also happen when an object's reference variable is assigned an explicit null value or is reinitialized.

So, if we apply this definition, the answer will be: object a . Here I repeat object and not the reference.We must make a distinction between the object and the reference!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM