Sitemap
The Ordinary Programmer

The Ordinary Programmer is for coders who embrace simplicity and practicality. We share real-world tips, project stories, and tech insights for developers at every level. You don’t need to be a superstar — just a programmer who loves to learn and build helpful software.

Member-only story

Decrypt Go: runtime.SetFinalizer

3 min readSep 6, 2024

--

Press enter or click to view image in full size
Author upload

If we want to do some resource release before an object is GC, we can use returns.SetFinalizer. It’s like executing defer to free resources before a function returns. For example:

List 1: Using runtime.SetFinalizer

type MyStruct struct {  
Name string
Other *MyStruct
}

func main() {
x := MyStruct{Name: "X"}
runtime.SetFinalizer(&x, func(x *MyStruct) {
fmt.Printf("Finalizer for %s is called\n", x.Name)
})
runtime.GC()
time.Sleep(1 * time.Second)
runtime.GC()
}

The official documentation explains that SetFinalizer associates a finalizer function with an object. When the garbage collector (GC) detects that an unreachable object has an associated finalizer, it will execute the finalizer and disassociate it. The object will be collected on the next GC cycle if it is unreachable and no longer has an associated finalizer.

While runtime.SetFinalizer can be helpful, there are a few critical points to keep in mind:

  • Deferred Execution: The SetFinalizer function will not execute until the object is selected for garbage collection. Therefore, avoid using SetFinalizer for…

--

--

The Ordinary Programmer
The Ordinary Programmer

Published in The Ordinary Programmer

The Ordinary Programmer is for coders who embrace simplicity and practicality. We share real-world tips, project stories, and tech insights for developers at every level. You don’t need to be a superstar — just a programmer who loves to learn and build helpful software.

huizhou92
huizhou92

Written by huizhou92

Golang backend engineer. Specializes in cloud, data, and security. Lifelong learner. Efficiency enthusiast.