Why is it that implementing finalize method causes performance overhead in Java?
The main reason:
Java postpones GC to almost very late stage - when we are kind of running out of memory - and then quickly clears several 100 MBs or GBs.
The finalize method is designed to run just before a method is GC'ed.
So, at a critical moment there will be about 10 million objects finalize method being executed!!
So, the finalize is not the right place to do anything.
The minute you stop using a resource, it has to be closed/released.
https://howtodoinjava.com/java/basics/why-not-to-use-finalize-method-in-java/
-
one can still set the
gcInterval
to a lower value (default is once per minute). so you are trying to imply, that you instance & destruct 10 million objects per minute? later version of Java don't even use it anymore. and such unreal number do not add more weight to the claim. – Martin Zeitler Nov 17 '18 at 8:34 -
Most Java programmers are taught to avoid finalize - and OP wants to know why. I am assuming he wants a simple answer. – Teddy Nov 17 '18 at 8:37
-
The article you posted has a section titled "Finalizers are not your friend".. So, I hope you are not reccommending implementing finalize method in user objects. – Teddy Nov 17 '18 at 8:38
-
I agree, there may be rare cases where finalize is useful. Just saying don't feel free to implement finnalize in every object OP likes. – Teddy Nov 17 '18 at 8:40
-
1NOTE: The Finalization Queue is a linked list so every object added to the finalization queue adds another object. – Peter Lawrey Nov 17 '18 at 10:14
finalize
method – flakes Nov 17 '18 at 8:19