问题
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.
- Invokes
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