Garbage Collection and Finalizers: Finer Points

后端 未结 3 1928
小蘑菇
小蘑菇 2020-12-05 08:23

In answering another question* on SO, and the subsequent comment discussion, I ran into a wall on a point that I\'m not clear on.

Correct me on any point where I\'m

3条回答
  •  余生分开走
    2020-12-05 09:06

    Objects that contain a finalizer tend to live longer. When, during a collect, the GC marks an object with a finalizer as being garbage, it will not collect that object (yet). The GC will add that object to the finalizer queue that will run after the GC has finished. Consequence of this is that, because this object is not collected, it moves to the next generation (and with that, all objects it refers to).

    The GC suspends all running threads. The finalizer thread on the other hand will run in the background while the application keeps running. The finalizer calls all finalize methods on all objects that are registered for finalization. After the finalizer method on an object has ran, the object will be removed from the queue, and from that point on the object (and possibly all objects it still references) is garbage. The next collection that cleans objects of the generation of that object will (at last) remove that object. Since objects that live in generation 2 are collected about 10 times as less as objects that live in generation 1, and gen 1 ten times as less as gen 0, it can take some time for such object is finally garbage collected.

    Because the finalizer thread is just a simple thread that runs managed code (it calls the finalizers), it can block and even dead lock. Because of this it is important to do as little as possible in finalize methods. Because the finalizer is a background thread, a failing finalize method could even bring down the complete AppDomain (yuck!).

    You could say that this design is unfortunate, but if you think about it, other designs where the framework cleans our mess effectively, are hard to imagine.

    So, to answer your questions:

    1. Yes, only after the object is removed from the finalizer queue, the object will be garbage and the GC will collect it.
    2. The GC suspends all threads, even the finalizer queue.
    3. The finalizer queue can deadlock. Lock as little as possible inside finalize methods.

提交回复
热议问题