Have you ever used PhantomReference in any project?

后端 未结 9 477
再見小時候
再見小時候 2020-11-29 17:02

The only thing I know about PhantomReference is,

  • If you use its get() method, it will always return null
9条回答
  •  天涯浪人
    2020-11-29 17:59

    if you use its get() method it will always return null, and not the object. [ then whats the use of it ]

    The useful methods to call (rather than get()) would be isEnqueued() or referenceQueue.remove(). You would call these methods to perform some action that needs to take place on the final round of garbage collection of the object.

    The first time around is when the object has its finalize() method called, so you could put closing hooks there too. However, as others have stated, there are probably more sure ways of performing clean up or whatever action needs to take place pre and post garbage collection or, more generally, upon end-of-life of the object.

提交回复
热议问题