Why are Phantom References not cleared as they are enqueued?

后端 未结 2 449
无人共我
无人共我 2020-12-15 07:04

We can see that "phantom reachable" is as unreachable as "unreachable": §

An object is phantom reachable if it is neither st

相关标签:
2条回答
  • 2020-12-15 07:34

    This was changed in JDK 9. Now phantom references are cleared as soft and weak references do. And the corresponding paragraph was removed from the Javadoc.

    Unlike soft and weak references, phantom references are not automatically cleared by the garbage collector as they are enqueued. An object that is reachable via phantom references will remain so until all such references are cleared or themselves become unreachable.

    0 讨论(0)
  • 2020-12-15 07:47

    Soft references are cleared when enqueued because the primary use of soft references are to allow caching of large objects, and clearing the soft references allows the large cached object to be garbage collected.

    Weak references are cleared when enqueued because the primary use of weak references are to allow one to reference an object without preventing it from being garbage collected, so clearing the references as soon as the object is enqueued allows the object to be garbage collected.

    Phantom references are not cleared when enqueued since one use case of phantom references is to allow performing cleanup before an object is garbage collected. By not clearing the references, the object remains phantomly reachable (and not eligible for garbage collected) until after the PhantomReference to that object is cleared by the user, or the PhantomReference is itself garbage collected.

    This is explained here,

    An object is phantom reachable if it is neither strongly, softly, nor weakly reachable, it has been finalized, and some phantom reference refers to it.

    Finally, an object is unreachable, and therefore eligible for reclamation, when it is not reachable in any of the above ways.

    0 讨论(0)
提交回复
热议问题