I have heard that in Joshua Bloch book written that allocation and memory collection might be increased to 430 times if we override finalize method.
It is clear for me that memory collection can work slower because additional iteration requred for gc to free memory.
But why allocation phase can be increased?
I have searched for the original statement:
So this isn’t a general statement, but just a report of evidence that suggests that there is a pattern behind it, not that the number is reproducible. This factor is likely to change when using not-so-trivial objects or just a lot more of them.
Of course, these costs depend on how finalization is actually implemented. In HotSpot, an instance of
Finalizer
will be created by calling theFinalizer.register
method every time an object with a non-trivialfinalize()
method is created.This might imply much more costs than just allocating two objects instead of one. These
Finalizer
instances will be strongly linked, which is necessary to prevent the collection of theFinalizer
instances themselves, and they have a reference to the constructed object. In other words, regardless of how local the object allocation initially was, the new object will escape, hindering lots of subsequent optimizations.When it comes to “destruction”, reclaiming an ordinary object is a no-op. No action will be taken and, in fact, it is impossible to do anything with the unreachable object, as it is unreachable. Special reachability states can only be encountered by having a reachable
Reference
object, like theFinalizer
object mentioned above, which holds a reference to the particular object (while the object wasn’t encountered through any other ordinary reference. Then, theReference
object can be enqueued, after which (one of) the finalizer thread(s) can take the appropriate action.Of course, comparing “no action” with any other action can lead to arbitrary factors. The absolute number was 2,400ns, which is reasonable for an action that involves enqueuing an object and notifying another thread to poll the queue.