组合对象的垃圾收集

组合对象的垃圾收集

本文介绍了组合对象的垃圾收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类

 类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> a 持有对 b 的引用。


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 to null. 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 setting b = 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 to a and a held a reference to b.

这篇关于组合对象的垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:37