Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What makes Finalizers so costly?

Tags:

java

finalizer

From Effective Java:

Oh, and one more thing: there is a severe performance penalty for using finalizers. 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.

What makes the Finalizers so costly ?

like image 829
Geek Avatar asked Jul 17 '12 14:07

Geek


2 Answers

http://www.ibm.com/developerworks/java/library/j-jtp01274/index.html

extract from link above

Objects with finalizers (those that have a non-trivial finalize() method) have significant overhead compared to objects without finalizers, and should be used sparingly. Finalizeable objects are both slower to allocate and slower to collect. At allocation time, the JVM must register any finalizeable objects with the garbage collector, and (at least in the HotSpot JVM implementation) finalizeable objects must follow a slower allocation path than most other objects. Similarly, finalizeable objects are slower to collect, too. It takes at least two garbage collection cycles (in the best case) before a finalizeable object can be reclaimed, and the garbage collector has to do extra work to invoke the finalizer. The result is more time spent allocating and collecting objects and more pressure on the garbage collector, because the memory used by unreachable finalizeable objects is retained longer. Combine that with the fact that finalizers are not guaranteed to run in any predictable timeframe, or even at all, and you can see that there are relatively few situations for which finalization is the right tool to use.

like image 109
nate_weldon Avatar answered Sep 18 '22 22:09

nate_weldon


The crucial difference is the very existence of a finalizer method, irrespective of what it does. As soon as the GC has finalizable objects, it must work much harder to get all the housekeeping right. It must mark them as finalizable, keep them in a pool, run finalization, check whether they're resurrected after that, juggle all kinds of multithreaded issues with finalizing code, and so on.

The difference can be seen most starkly in the GC's young generation: in an optimistic, and not entirely rare scenario, the GC'ing boils down to a single operation: decrementing the pointer to the first available memory address. With finalizers, it's the whole process outlined above.

like image 36
Marko Topolnik Avatar answered Sep 22 '22 22:09

Marko Topolnik