Why do finalizers have a “severe performance penalty”?

Because of the way the garbage collector works. For performance, most Java GCs use a copying collector, where short-lived objects are allocated into an “eden” block of memory, and when the it’s time for that generation of objects to be collected, the GC just needs to copy the objects that are still “alive” to a more permanent storage space, and then it can wipe (free) the entire “eden” memory block at once. This is efficient because most Java code will create many thousands of instances of objects (boxed primitives, temporary arrays, etc.) with lifetimes of only a few seconds.

When you have finalizers in the mix, though, the GC can’t simply wipe an entire generation at once. Instead, it needs to figure out all the objects in that generation that need to be finalized, and queue them on a thread that actually executes the finalizers. In the meantime, the GC can’t finish cleaning up the objects efficiently. So it either has to keep them alive longer than they should be, or it has to delay collecting other objects, or both. Plus you have the arbitrary wait time of actually executing the finalizers.

All these factors add up to a significant runtime penalty, which is why deterministic finalization (using a close() method or similar to explicitly finalize the object’s state) is usually preferred.

Leave a Comment