问题描述
我有两个类
类A
持有对
{
//构造函数
}
类别B
{
private A a;
public B()
{
a = new A();
$ b假设我使用B的对象[比如b
]在我的代码中,在我最终使用它之后,我将它设置为null
。我知道B的对象现在可用于垃圾收集。
我知道在将b设置为null后,它会立即符合条件进行垃圾回收。但是,类型A的目标呢?将B设置为
null
之后立即可用于垃圾回收吗?或者在B被垃圾收集后 垃圾收集 ?理论上,直到B被垃圾收集,a
仍然有对它的引用?因此,在设置b = null
;
解决方案后,SUN JVM编译器会立即检测到这一点。 GC足够聪明地跟踪对象图中的路径,以检查对某些对象的现有引用是否可访问。它甚至可以检测周期(就你而言,如果
b
持有对a
和<$ c $的引用c> ab
的引用。I have two classes
Class A { //constructor } Class B { private A a; public B() { a = new A(); } }
Suppose I use an object of B [say
b
] in my code and after I end up using it, I set it tonull
. I know that the object of B is now available for garbage collection.I know that after setting b to null, it will be immediately eligible for garbage collection? But what about the object of type A? Will it be available for garbage collection immediately after I set B to
null
? Or will it be eligible for garbage collection after B is garbage collected?Theoretically, until B is garbage collected,
a
still has a reference to it? So will the SUN JVM compiler detect this immediately after settingb = null
;解决方案The GC is smart enough to follow paths in graphs of objects in order to check if the existing references to some object are reachable. It can even detect cycles (like, in your case, if
b
held a reference toa
anda
held a reference tob
.这篇关于组合对象的垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!