15.3k views
1 vote
Are objects that have finalizers deleted the first time automatic 'Garbage Collections' occurs?

1 Answer

5 votes

Final answer:

Objects that have finalizers are not deleted in the initial garbage collection cycle. They are enqueued for finalization and can only be collected in a subsequent cycle after the finalizer has been run.

Step-by-step explanation:

Objects with finalizers (or destructors in some programming languages) are not necessarily deleted during the first garbage collection pass. When a garbage collector finds an object with a finalizer and it is the first time the object is eligible for collection, it typically places the object onto a finalization queue. The actual finalizer code runs at a later time, determined by the garbage collector, which can lead to a delay in memory being freed.

Once the finalizer has run and if the object is no longer reachable, it can be collected during a subsequent collection pass. So, it typically requires at least two garbage collection cycles to fully reclaim the memory of an object with a finalizer: one cycle to detect the object is eligible for finalization and to enqueue it for finalization, and another cycle to actually remove the object after finalization.

User Robin Moffatt
by
7.1k points