2

Why is it that implementing finalize method causes performance overhead in Java?

Tck
  • 83
  • 6

1 Answers1

1

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/

Teddy
  • 4,009
  • 2
  • 33
  • 55
  • 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 08: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 08: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 08: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 08:40
  • "being taught to" is not exactly the same as "knowing what is actually going on"... while there barely should be heavy code, that would make sense in an implementation of `finalize()`. I mean, the purpose of it always were rare cases. – Martin Zeitler Nov 17 '18 at 08:41
  • Please guess what level of information OP is looking for. If he is an expert looking for intricate details, I am sure, he will ask for more such info. I'm assuming its a beginner question. – Teddy Nov 17 '18 at 08:43
  • as I see it ...it is a myth being presented as a fact. slowing down the GC does not affect run-time. – Martin Zeitler Nov 17 '18 at 08:44
  • @MartinZeitler The link you shared has a section titled "Finalizers are not your friend"!! – Teddy Nov 17 '18 at 08:45
  • Apparently finalize method has been deprecated in Java 9 :O – Teddy Nov 17 '18 at 08:53
  • https://hackernoon.com/java-lang-object-finalize-is-finally-deprecated-f99df40fa71 – Teddy Nov 17 '18 at 08:54
  • I'd agree as far as, that calling `.finalize()` is basically pointless (hence it will be called, no matter what) and that implementing it slows down the GC... which might be both reasons for it having been deprecated. – Martin Zeitler Nov 17 '18 at 09:33
  • 1
    NOTE: 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