If instance variables still have references, will Java GC destroy the object?

I've read some Java garbage collection guides online, but I'm still a little unclear, and make sure there are no memory leaks in my code

Does the Java GC collect objects that have lost references, but whose variables still have references?

So let's say someobject:

public class SomeObject {
    public ObjectVar var;

    public SomeObject() {
        var = new ObjectVar();
    }
}

And my code:

SomeObject obj1 = new SomeObject();
SomeObject obj2 = new SomeObject();
obj2.var = obj1.var;
obj1 = null;

So obj1 has a reference to VaR, but obj1 no longer has any reference So GC will destroy obj1, but will keep var alive? I suppose so; I just want to make sure thank you!

Solution

This will be what will happen (see comments below)

// obj1 and obj1.var get created
SomeObject obj1 = new SomeObject();
// obj2 and obj2.var get created
SomeObject obj2 = new SomeObject();
// old obj2.var becomes eligible for GC
obj2.var = obj1.var;
// obj1 becomes eligible for GC
obj1 = null;

Finally, there are still two objects that will not get GCD – obj2, while the previous obj1 VaR is now referenced as obj2 var.

Note: in a special case, objectvar class is a non static internal class of someobject, which maintains the control over obj1 The reference to var will also remain obj1 This is because someobject There is a hidden variable of type someobject inside the objectvar class, which references the external object of the inner class

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>