开发者

What's happening with the Java GC when I move out of scope but still hold a reference?

Basically i'm fairly new to Java and i'm trying to get my head round the following.

public class Test {

TestObject objectA;

 public static void main(String args[])
 {
     Test t = new Test();
     t.test();
     while (true){
         try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {}
         System.out.println("Obj A: " + t.objectA.toString()); 
     }
 }

 void test(){
     Object objectB = new TestObject(1, 1);

     objectA = (TestObject)objectB;
     System.out.println("Obj B: " + objectB);

     objectB = null;     System.out.prin开发者_运维技巧tln("Obj B: " + objectB);
 }

}

Output:

Obj B: TestObject@525483cd 

Obj B: null

Obj A: TestObject@525483cd

Obj A: TestObject@525483cd

Basically, i'm creating a local object objectB in the Method test() and assigning it's reference to the variable objectA inside the Test object.

I then set the local variable to null and verify the reference has been nulled.

Now from my understanding here i've just effectively nulled a pointer to the object. The object still exists with objectA holding the only reference. Does this mean that the garbage Collector will not collect the object that was created in a method with narrow scope?

If i nulled the pointer to objectA will my object be collected?

Sorry if this seems like an obvious question with an answer I just need to be sure I'm understanding what i've already read.


Yes, making objectA point to the object keeps it from being collected. And yes, removing the last remaining reference makes the object eligible for collection.

It's important to say "makes eligible for collection" instead of "is collected" -- the object probably won't be collected right away, or maybe even never if the JVM never needs the memory again.


Yes you're right an object is eligible for garbage collection if there is no reference to it. More precisely if it cannot be accessed from a reference in your code (example of 3 objects referencing each other but no reference variable in your code can access one of them):

For instance:

A -> B

B -> C

C -> A

but no reference to A, B and C => all three are eligible for GC.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜