When is finalize() invoked during garbage collection?

泄露秘密 提交于 2021-02-16 14:59:41

问题


From :

Q11 of https://www.baeldung.com/java-memory-management-interview-questions

When an object becomes eligible for GC, the garbage collector has to run the finalize() on it; this method is guaranteed to run only once, thus the collector flags the object as finalized and gives it a rest until the next cycle.

I have a few questions to ask:

  • Is that statement correct?
  • Is it during the marking phase, does the garbage collector invoke the finalize() method?
  • Why does it give a rest until the next cycle?

P.S: I do understand that finalize() is finally deprecated in Java 9. Thanks to good soul who decided to make it so.


回答1:


Is it during the marking phase, does the garbage collector invoke the finalize() method?

Implementation dependent, but generally no. The finalizer is called by a background thread after GC completes.

Remember, GC may be a stop-the-world event, and should be as short as possible. Finalizer methods may be slow, so they should not be called during GC.

Why does it give a rest until the next cycle?

At a high level (simplified), it operates as follows (see JLS 12.6.1 for terms):

  • GC detect objects that are not reachable:

    • If object has a finalizer method, add it to the finalizer queue.
      The object is finalizable.

    • If the object is reachable from an finalizable object, leave it.
      The object is finalizer-reachable.

    • Otherwise reclaim memory now.
      The object was unreachable.

  • Background Finalizer thread processes queued finalizable objects:

    • Invokes finalize() method.
      When method returns, the object is finalized.
  • Since GC has already completed, finalized objects are "resting" until next GC cycle.

  • On next GC cycle, objects with a finalizer method that is marked finalized is treated as unreachable, and memory will be reclaimed (assuming finalizer method didn't make the object reachable again).

Note that many GC cycles may occur while an object is finalizable, i.e. it may take a while for the Finalizer thread to process the object.



来源:https://stackoverflow.com/questions/53905181/when-is-finalize-invoked-during-garbage-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!