Search code examples
javagarbage-collectionjava-memory-modelfinalizefinalization

why allocation phase can be increased if we override finalize method?


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?


Solution

  • I have searched for the original statement:

    On my machine, the time to create and destroy a simple object is about 5.6 ns. Adding a finalizer increases the time to 2,400 ns. In other words, it is about 430 times slower to create and destroy objects with finalizers.

    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 the Finalizer.register method every time an object with a non-trivial finalize() 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 the Finalizer 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 the Finalizer object mentioned above, which holds a reference to the particular object (while the object wasn’t encountered through any other ordinary reference. Then, the Reference 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.