取消引用对象但仍引用其成员对象时会发生什么? [英] What happens when an object is dereferenced but its member object is still referenced?
问题描述
class ClassA {
ClassB mem1 = new ClassB();
ClassB mem2 = new ClassB();
}
class ClassB {
}
public class Sample {
public static void main(String[] args) {
ClassA obj1 = new ClassA();
ClassB obj2 = obj1.mem1;
obj1 = null;
obj2 = null;
}
}
在上面的程序中,行后会发生什么: obj1 = null
?
In the above program, what happens after the line: obj1 = null
?
obj1 已准备好进行垃圾回收,即使其中一个成员对象仍然被引用?
Is obj1 ready for garbage collection even though one of its member object is still being referenced?
推荐答案
自动垃圾收集是查看堆内存的过程,识别哪些对象正在使用哪些对象,以及删除未使用的对象。使用中的对象或引用的对象意味着程序的某些部分仍然维护指向该对象的指针。程序的任何部分都不再引用未使用的对象或未引用的对象。因此,可以回收未引用对象使用的内存。
Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.
在这种情况下,处理 obj1 = null;
没有引用它指向的 ClassA
类型的对象,所以它是垃圾收集资格。 ClassB
对象, mem1
但仍然以 obj2 $的形式提供引用c $ c>并保持至少直到行
obj2 = null;
被执行。
In this context, when obj1 = null;
is processed there are no references to the object of type ClassA
to which it points, and so it is eligable for garbage collection. The ClassB
object, mem1
however still has a reference in the form of obj2
and so is kept at least until the line obj2 = null;
is executed.
这篇关于取消引用对象但仍引用其成员对象时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!