How finalizable objects takes at least 2 garbage collection cycles before it can be reclaimed?

前端 未结 2 1900
忘掉有多难
忘掉有多难 2020-12-19 23:14

I\'m reading this article and I can\'t really understand how the finalizable objects (objects which override the finalize method) takes at least 2 GC cy

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-19 23:18

    Though you got your answer (which is absolutely correct), I want to add a small-ish addendum here. In general, references are of two types : strong and weak. Weak References are WeakReference/SoftReference/PhantomReference and Finalizer(s).

    When a certain GC cycle traverses the heap graph and sees one of these weak references, it treats it in a special way. When it first encounters a dead finalizer reference (let's consider this being the first GC cycle), it has to resurrect the instance. finalize is an instance method, and it needs an actual instance to be invoked. So a GC first saw that this Object is dead, only to revive it moments later, to be able to call finalize on it. Once it calls that method on it, it marks the fact that it has already been called; so when the next cycle happens, it can be actually be GC-ed.

    It would be incorrect to call this the second GC.

    For example G1GC does partial clean-up of the heap (young and mixed), so it might not even capture this reference in the next cycle. It might not fall under its radar, as simple as that.

    Other GCs, like Shenandoah, have flags that control on which iteration to handle these special references (ShenandoahRefProcFrequency, 5 by default).

    So indeed there is a need for two cycles, but they do not have to be subsequent.

提交回复
热议问题