So, here’s something interesting, there’s an API in Go’s runtime package called runtime.SetFinalizer. This little feature lets you s

Go Runtime Finalizer and Keep Alive

submited by
Style Pass
2024-11-09 02:00:04

So, here’s something interesting, there’s an API in Go’s runtime package called runtime.SetFinalizer. This little feature lets you set a “finalizer” for an object.

Now, a finalizer is basically a function tied to an object that’s meant to run once the garbage collector decides that the object’s no longer needed.

In this code, I’ve got a pointer referencing an instance of a FourInts struct, and then I set a finalizer for it. So, when the garbage collector runs, it’ll call the finalizer once that object is no longer needed, which in this case means printing out a message.

Now, Go’s garbage collector will eventually trigger the finalizer, but it won’t happen exactly when the object’s no longer in use. The finalizer will run, but there’s no specific guarantee on timing. It’s unpredictable, meaning you can’t count on it for any immediate actions.

Since Go’s garbage collector operates behind the scenes, the timing of finalizers depends entirely on the GC cycle. This unpredictability gives finalizers a kind of “magic” quality that, well, we Gophers tend not to be big fans of. Go doesn’t really encourage using finalizers like destructors in other languages, mainly because relying on them this way can lead to memory leaks if GC doesn’t happen when you’re hoping it will.

Leave a Comment