Manage lifetimes: finalizers, cleanup, weak references and KeepAlive
Manage lifetimes: finalizers, cleanup, weak references and KeepAlive
Prefer explicit Close and defer for scarce resources. runtime.SetFinalizer and runtime.KeepAlive exist in Go 1.23. A finalizer can run after an object becomes unreachable, but timing is not guaranteed and finalizers may not run before exit. Cycles, tiny allocations and resurrected objects complicate lifetime. KeepAlive marks an object as live through a particular point; it does not pin memory or synchronize goroutines. Go 1.24 introduced runtime.AddCleanup and package weak. A cleanup should receive independent resource state, not capture or retain the target object. A weak pointer does not keep its target alive; Value may return nil and must be checked.
package main
import ( "fmt")
type Resource struct{ closed bool }
func (r *Resource) Close() { r.closed = true }func main() { r := &Resource{} func() { defer r.Close(); fmt.Println(r.closed) }() fmt.Println(r.closed)}This toy resource demonstrates deterministic release at scope exit, not actual file I/O. For real resources check Close errors where relevant. A fallback finalizer or cleanup must not double-close an already released resource. Do not wait for GC to release a file, socket or transaction.
Expected output:
falsetrueKeep an owner alive across an operation
package main
import ( "fmt" "runtime")
type Owner struct{ data [32]byte }
func use(x byte) byte { return x + 1 }func main() { p := &Owner{} p.data[0] = 7 runtime.SetFinalizer(p, func(*Owner) {}) result := use(p.data[0]) runtime.KeepAlive(p) runtime.SetFinalizer(p, nil) fmt.Println(result)}The scalar operation models a resource operation; no actual descriptor is used. KeepAlive after the operation prevents premature finalization through that point. Clearing the finalizer while p remains reachable avoids relying on asynchronous execution. In Go 1.24+, runtime.AddCleanup(p, f, arg) returns a Cleanup handle; Stop cancels a cleanup that has not been queued, with p kept reachable across Stop. weak.Make(p) produces a weak.Pointer[T]; obtain a strong pointer using Value and use it only if nonnil. These newer APIs are documentation-checked, not executable in the local Go 1.23.2 toolchain. Neither API guarantees callback timing. Cleanup functions can execute concurrently in Go 1.25 onward; protect shared resource state.
Expected output:
8Try it locally
Implement an idempotent explicit Close on a toy resource: the first call returns true and the second false. This example is single-threaded; concurrent use would require synchronization.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Garbage collection 06: Manage lifetimes: finalizers, cleanup, weak references and KeepAlive
Check the lesson objective before moving on.
What is the preferred way to release a scarce resource promptly?
What does weak.Pointer.Value require?