

When everything you know about finalizers is wrong - AndrewDucker
http://ericlippert.com/2015/05/18/when-everything-you-know-is-wrong-part-one/

======
TheLoneWolfling
Are there any languages that get finalizers right?

As in, are there any languages that at least make a best effort to run
finalizers?

To me, it seems like languages like Java and C# go "we can't do it in every
conceivable situation, so let's punt it always". Not an ideal "solution". You
don't see optimizers optimizing functions to "throw OutOfMemoryError", so why
do they do the equivalent with finalizers?

------
scarmig
Is there ever actually a good reason to use finalizers? Why do they even
exist?

It seems like the things you want them to do, they actually don't provide the
guarantees necessary to do them; and the things they are guaranteed to do, are
so minimal that no one actually wants to do them.

~~~
millstone
I think they make sense for the case of resources that need explicit
deallocation, when their lifetime is not tied to a scope (e.g. multiple
owners).

An example is a Lock object that wraps a pthread_mutex. It's unreasonable to
demand that every object that has a lock explicitly dispose of it; it's
simpler to equip the Lock with a finalizer that can dispose of the underlying
mutex.

~~~
fleitz
Except finalizers may not release the mutex if they aren't run

~~~
eel
If your application is a well-behaving application in a well-behaving
environment, then it will most likely run in a reasonable amount of time.
Furthermore, if you leak a few mutexes, it's not really a big deal for most
applications.

I think one of the implied points of the article is that you should not rely
on finalizers for anything time sensitive or critical. For instance, if you
MUST close a file handle or database connection, you should never rely on a
.NET finalizer to do it because it's not predictable when or if it will run.
You should explicitly close it (most likely by implementing and calling
Dispose().)

