Garbage collection of Composed Objects

前端 未结 5 2244
青春惊慌失措
青春惊慌失措 2021-01-05 11:10

I have two classes

Class A
{
    //constructor
}

Class B
{
    private A a;

    public B()
    {
        a = new A();
    }
}

Suppose I u

相关标签:
5条回答
  • 2021-01-05 11:15

    Object A will also become eligible garbage collection as soon as you set ObjectB to null (* condition is ObjectA is not referred by any other live object). This condition is known as "Island of Isolation".

    Here is a nice explanation of this situation. (Here is one more explanation from SCJP book)

    0 讨论(0)
  • 2021-01-05 11:16

    Once there are no hard references to b there is no way to reach its reference to a, so both are eligible for garbage collection as far as I know.

    0 讨论(0)
  • 2021-01-05 11:25

    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.

    0 讨论(0)
  • 2021-01-05 11:27

    There are also some flags you can use when running a Java program (at least with the Sun JVM) that will give some debugging information about what goes on during garbage collection. Try the -verbose:gc option.

    http://download.oracle.com/javase/6/docs/technotes/tools/solaris/java.html

    0 讨论(0)
  • 2021-01-05 11:32

    Generally, you shouldn't care. It's not reachable, and you should let the garbage collection worry about the rest. Since it becomes unreachable, it should be eligeble for collection immediately.

    0 讨论(0)
提交回复
热议问题