如果实例变量仍然有引用,Java GC是否销毁对象? [英] Does Java GC destroy objects if instance variables still have reference?
问题描述
我已经在网上阅读了一些Java垃圾收集指南,但是我还是有点不清楚,希望确保我的代码中没有内存泄漏。
Java GC是否收集失去引用的对象,但它的变量仍然有引用?
假设我有SomeObject:
public class SomeObject {
public ObjectVar var;
$ b $ public SomeObject(){
var = new ObjectVar();
$ / code $ / pre
和我的代码:
SomeObject obj1 = new SomeObject();
SomeObject obj2 = new SomeObject();
obj2.var = obj1.var;
obj1 = null;
所以obj1的var有引用,但obj1不再有任何引用。那么,GC是否会销毁obj1,但保持var还活着? (我假设如此,只是想确定)。谢谢!
解决方案这里将会发生什么(见下面的评论)
// obj1 and obj1.var get created
SomeObject obj1 = new SomeObject();
// obj2和obj2.var获得创建
SomeObject obj2 = new SomeObject();
// old obj2.var成为符合GC
的条件obj2.var = obj1.var;
// obj1变为符合GC
obj1 = null;
最后,仍有两个对象没有得到GCd - obj2
和前 obj1.var
,现在引用为 obj2.var
。
注意:在 ObjectVar
类的特殊情况下,类是的非静态内部类SomeObject
,保持对 obj1.var
的引用也会保持 obj1
。这是因为在内部, SomeObject.ObjectVar
类有一个类型为 SomeObject
的隐藏变量,它引用内部类。
I've read through some of the Java garbage collection guides online, but I'm still a bit unclear and wanted to make sure so that I don't have memory leaks in my code.
Does Java GC collect objects that lost its reference, but its variables still have reference?
So let's say I have 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's var has reference, but obj1 no longer has any reference. So, will the GC destroy obj1, but keep var alive? (I'm assuming so; just wanted to make sure). Thanks!
解决方案 Here is what is going to 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;
In the end, two objects remain that do not get GCd - obj2
and the former obj1.var
which is now referenced as obj2.var
.
Note: In a special case of ObjectVar
class being a non-static inner class of SomeObject
, keeping a reference to obj1.var
would also keep obj1
around. This is because internally the SomeObject.ObjectVar
class has a hidden variable of type SomeObject
, which references the outer object of the inner class.
这篇关于如果实例变量仍然有引用,Java GC是否销毁对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!