Upon new A(), we allocate sufficient amount of memory to hold all object that A contains.
Object A() may contain other objects like B() and C()
Question 1: When A() is no longer needed and you want to remove it from the heap, will setting it's reference to null do the trick? (If not, what would be the right way to signal the JVM to GC this object now?)
Question 2: If so, what happens with the instances pointing to B() and C()
Question 3: Is there a way this effect can be observed? (memory being deallocated to free up the object)
Setting A to null will mark A as a candidate to be freed by the GC. Instances of B and C will be marked too if the only references to those instances were from instance A.
Edit about question 3: A simple way to debug this effect is using the method finalize; When an object is GC´ed, his finalize is called .
However, be careful with this method: finalize is not guaranteed to be executed always (as the GC is not guaranteed to free an object) and should never be used for application´s general purposes.
There are better debugging tools depending on your IDE. For example, in eclipse: http://www.yourkit.com/docs/80/help/garbage_collection.jsp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With