Go: Finalizers
ℹ️ This article is based on Go 1.12.
Go runtime provides a method runtime.SetFinalizer
that allows developers to attach a function to a variable that will be called when the garbage collector sees this variable as garbage ready to be collected since it became unreachable. This feature is highly subject to debate and this article does not aim to participate in it, but rather to explain the implementation of the method.
No guarantees
Let’s take an example of a program that uses finalizers:
This program will create, in a loop, three instances of a struct and attach a finalizer to it. Then, the garbage collector will be called to collect the instances created previously. Running this program will give us the following output:
31
37
47
As we can see, finalizers have not been called. The documentation of the runtime could explain this point:
The finalizer is scheduled to run at some arbitrary time after the program can no longer reach the object to which obj points. There is no guarantee that…