Garbage collection of composite objects

I have two classes

Class A { //constructor } Class B { private A a; public B() { a = new A(); } } 

Suppose I use object B [say b ] in my code, and after I use it, I set it to null . I know that object B is now available for garbage collection.

I know that after setting b to null it will be immediately suitable for garbage collection? But what about an object of type A? Will it be available for garbage collection right after I set B to null ? Or will it be acceptable to collect garbage after B is a garbage collector ?

Theoretically, until B is garbage collected, does it still have a link to it? Thus, the SUN JVM compiler detects this immediately after setting b = null ;

+7
source share
5 answers

GC is smart enough to track paths in object graphs to check if existing references to any object are available. It can even detect loops (for example, in your case, if b contained a link to a and a , contained a link to b .

+5
source

After there are no hard links to b, there is no way to get to the link to a, so both are entitled to garbage collection, as far as I know.

+3
source

As a rule, you don't care. This is not possible and you must let the trash can worry about everything else. As it becomes unavailable, it must be immediately removed for collection.

0
source

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

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

0
source

Object A will also be a suitable garbage collection as soon as you set ObjectB to null (* condition - ObjectA is not passed to any other living object). This condition is known as the “Isolation Island”.

Here is a good explanation of this situation. ( Here is another explanation from the SCJP book)

0
source

All Articles